Using days of the week for aggregates in DB2

为君一笑 提交于 2019-12-11 15:43:40

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/57726952/using-days-of-the-week-for-aggregates-in-db2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!