如何从Room数据库返回总和? [英] How to return sum from Room database?

查看:71
本文介绍了如何从Room数据库返回总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Expense对象获取值字段的总和,并将其显示在textview中,但是我真的不知道如何在Room Database中进行操作.我需要在Dao中创建特定的查询,还是有其他方法?

I need to get sum of the value field from Expense object and display this in textview, but I really don't know how to do it in Room Database. I need to create specific query in Dao or there is some other way?

Pojo:

@Entity(tableName = "expense_table")
public class Expense {

@PrimaryKey
private int id;
private String note;
private Double value;
private String type;

道:

@Dao
public interface ExpenseDao {

@Insert
void insertExpense(Expense expense);

@Query("SELECT * FROM expense_table")
LiveData<List<Expense>> getExpensesByDay();

推荐答案

您需要在DAO中创建一个新查询

You need to create a new query in DAO

@Query("SELECT COALESCE(sum(COALESCE(value,0)), 0) From expense_table")
LiveData<Double> getTotal();

这篇关于如何从Room数据库返回总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆