如何从Room数据库中返还总和?

问题描述 投票:0回答:1

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

唱:

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

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

DAO:

@Dao
public interface ExpenseDao {

@Insert
void insertExpense(Expense expense);

@Query("SELECT * FROM expense_table")
LiveData<List<Expense>> getExpensesByDay();
android android-room
1个回答
1
投票

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

@Query("SELECT COALESCE(sum(COALESCE(value,0)), 0) From expense_table")
LiveData<Double> getTotal();
© www.soinside.com 2019 - 2024. All rights reserved.