如何从Room数据库返回总和?

时间:2019-02-28 16:56:05

标签: android android-room

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

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();

1 个答案:

答案 0 :(得分:2)

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

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