Reputation: 5105
I currently have a query that reads from a table which is written to daily, so I have totals for every day.
What I'm trying to do is modify this query so that I can use days of the week as an aggregate, if that makes sense.
THe totals I get right now are correct, but I want to use Sunday through Saturday as a week and effectively say ``'If today is wednesday, sum totals for weeklyData for Sunday, MOnday and Tuesday from tableOne```
I have this query:
SELECT employee,
sum(case when category = 'Brown' then daily_total else 0 end) as DailyBrownNumbers,
sum(case when category = 'Brown' then weekly_quota else 0 end) as WeeklyBrownNumbers,
CURRENT_DATE as DATE_OF_REPORT
from dailyRecords
where date_of_report >= current_date
group by employee
which reads from that table for the daily records and that's what I need still, but I want to add a sum for daily_total based on those days of the week if possible.
Can this be done with DB2?
Upvotes: 0
Views: 425
Reputation: 583
You can use dayofweek function. SQL gets all records starting from Sunday including current date. Second column "DailyBrownNumbers" uses case statement to restrict totals to current date records. Third column "WeeklyTotal" has totals for all records from Sunday.
SELECT employee,
sum(case when category = 'Brown' and date_of_report >= current date
then daily_total
else 0 end) as DailyBrownNumbers,
sum(case when category = 'Brown'
then daily_total
else 0 end) as WeeklyTotal,
sum(case when category = 'Brown'
then weekly_quota
else 0 end) as WeeklyBrownNumbers,
CURRENT_DATE as DATE_OF_REPORT
from dailyRecords
where date_of_report >= ( current date - ( dayofweek(current date) - 1 ) days )
group by employee
Upvotes: 1