I am writing an android application storing workout dates and calories burned. Below is an example of the data in my table:
this is returned by:
SELECT month, day, calories FROM workouts ORDER BY year ASC, month ASC, day ASC LIMIT 12;
(month | day | calories)
3|2|714
3|3|945
3|4|630
3|10|446
3|16|396
3|20|255
3|22|108
3|23|112
3|23|169
3|23|2160
the code i’ve written for the above is:
public Cursor getLastTwelveDays(){
Cursor c;
String[] s = {KEY_MONTH, KEY_DAY, KEY_CALORIES};
String order = KEY_YEAR + " ASC, " + KEY_MONTH + " ASC, " + KEY_DAY + " ASC LIMIT 12" ;
c = db.query(WORKOUT_TABLE, s, null, null, null, null, order);
return c;
}
I would like to combine the rows with the same day and month into a single row like so:
3|2|714
3|3|945
3|4|630
3|10|446
3|16|396
3|20|255
3|22|108
3|23|2441 (112 + 169 + 2160)
Also, it would be nice if it were easy to use with android’s query function.
Thanks in advance.
What you are looking for is the group by clause. Use the SUM() method to get the total calories for each date. I believe the group by clause should go before the ORDER BY clause.
SELECT month, day, SUM(calories) FROM workouts GROUP BY month, day