简体   繁体   中英

In Room db Dao class- how to get values from table by comparing distinct values of a column?

I'm working on Room database, and I want to get two columns values(Category and total amount) from IncomeExpense table by comparing distinct values in category column. Let me explain, for example in category column there are 4 rows which have same value(cash), what I want is to calculate total amount of amount column where category is cash and category value (which is cash in this case). I take these categories values from another table (Category table) in which user can add edit or delete categories.
The problem is that I don't know how to compare category with those values user added in category column which dynamic in this case.

This is my Entity class.

@Entity
public class IncomeExpense  {
    @PrimaryKey(autoGenerate = true)
    private int id =0;

    private String type;
    private int amount;
    private String category;
    private String date;
    private String time;
    private String mode;
    private String note;

This is Dao class where I have to write this query

@Query("SELECT SUM(amount), category from IncomeExpense WHERE category like 'What should I write here to get these values in this case'");

I just want to get the total amount and category value in this case

you can use group by clause, this will return a list on IncomeExpense but amount will be grouped as per category

@Query("SELECT SUM(amount) as amount,category from IncomeExpense GROUP BY category");
public List<IncomeExpense> getCategoryPrice();

For Example: Database Has: [ (10, Cash), (50, Cash), (20, Credit), (10, Credit) ]

The above query will return [ (60, Cash), (30, Credit) ]

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