Reputation: 242
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
Upvotes: 2
Views: 1003
Reputation: 810
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) ]
Upvotes: 2