I have a table that store recent information about Department and bills. My goal is to find the last seven days activities from today date, categorize them by the Department and add up the price and return them as an array.
mysql> select * from Item;
+----+------------+--------------+
| ID | Department | Price | Date
+----+------------+--------------+
| 1 | DELL | 20 | 04/01/2019
| 2 | HP | 15 | 04/16/2019
| 3 | DELL | 30 | 03/15/2019
| 4 | ACER | 15 | 04/16/2019
| 5 | ASUS | 60 | 04/15/2019
| 6 | HP | 15 | 04/14/2019
| 7 | DELL | 30 | 03/30/2019
| 8 | ACER | 15 | 01/16/2019
| 9 | ASUS | 60 | 02/15/2019
+----+------------+----------+
So far I ordered the table by date:
Cursor cursor = db.rawQuery("SELECT * FROM " + Projects_TABLE + " ORDER BY " + PRO_DATE + " DES", null);
and compared the today date minus 7 days stored inside the table, but I don't know how to return every Department accord in the seven days with an added price for example, wanted results of an array:
Today Date is 04/16/2019
+----+------------+----------+
| ID | Department | Price
+----+------------+----------+
| 1 | HP | 30
| 2 | ACER | 15
+----+------------+----------+
Here is My code
public ArrayList<DetailedProject_GS> DB_Display_The_Progress_Weakly() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase ();
Cursor cursor = db.rawQuery("SELECT * FROM " + Projects_TABLE + " ORDER BY " + PRO_DATE + " DES", null);
ArrayList<DetailedProject_GS> ProjectsArchive = new ArrayList<>();
Calendar EndTime = Calendar.getInstance();
cursor.moveToFirst ();
while (cursor != null && cursor.getCount () > 0 && !cursor.isAfterLast ()) {
try {
SimpleDateFormat simpleDateFormat = new
SimpleDateFormat("EEEE dd/MM/yyyy" , Locale.ENGLISH);
String currentDateandTime = simpleDateFormat.format(new Date());
Calendar c = Calendar.getInstance();
c.setTime(simpleDateFormat.parse(currentDateandTime));
c.add(Calendar.DATE, -7);
EndTime.setTime(sdf.parse(cursor.getString (cursor.getColumnIndex (PROJECT_H_ENDTIME)) ));// all done
if (EndTime.after(c)){
//Adding CODE HERE
ProjectsArchive.add(data);
}else{
}
} catch (ParseException e) {
e.printStackTrace();
}
cursor.moveToNext ();
}
cursor.close();
sqLiteDatabase.close ();
return ProjectsArchive;
}
If you change the format of the dates to YYYY-MM-DD
, then all you need is group by department
:
select
department,
sum(price) price
from item
where date >= datetime('now', '-7 day')
group by department
With the current format of the dates, first you must convert it to YYYY-MM-DD
:
select
department,
sum(price) price
from item
where substr(date, 7) || '-' || substr(date, 1, 2) || '-' || substr(date, 4, 2) >= datetime('now', '-7 day')
group by department