简体   繁体   中英

How to return sum from Room database?

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:

@Dao
public interface ExpenseDao {

@Insert
void insertExpense(Expense expense);

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

You need to create a new query in DAO

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM