【发布时间】:2019-08-30 15:59:49
【问题描述】:
我目前有一个从表中读取并根据类别进行聚合的查询。它给了我我需要的东西,但我正在尝试添加另一列,查看过去一周中该类别/员工组合的所有记录。因此,如果使用此查询的作业在周三晚上运行,则需要获取周一和周二晚上的所有类别/员工记录的总数。
查询:
SELECT employee,
sum(case when category = 'Shoes' and date_of_report >= current_date - 1 days then daily_total else 0 end) as Shoes_DAILY,
sum(case when category = 'Shoes' and date_of_report >= ( current date - ( dayofweek(current date) - 1 ) days ) then sum(daily_total) else 0 end) as dailyTotalWeek
from shoeTotals
where date_of_report >= current_date
group by employee;
所以第三列有什么让我搞砸了,说函数使用无效。这就是我想要的:
源表有这些过去一周的记录:
employee | daily_total | date_of_report
--------------------------------------------------
123 14 2019-08-26
123 1 2019-08-27
123 56 2019-08-28
123 6 2019-08-29
123 8 2019-08-30 * today
我想要的输出将获得(基于员工和类别)今天的总数 (8),然后是该类别在每个前一个工作日的所有员工记录的总和。如上所示,在星期一晚上运行只会计算当天的记录,星期五晚上会计算星期一到星期五的记录。
employee | shoes_daily | dailyTotalWeek
--------------------------------------------------
123 8 85
我在使用 dayofweek 函数时做错了什么?
【问题讨论】:
-
我会查看分析/窗口函数,以按一年中的一周对您的列分区求和。然后只报告一年中的当前一周。
-
但这每晚运行,所以每天晚上我都会从今天的显式记录中获取每日数据,但我只希望第二列将运行前那一周的几天的值相加日期。有没有办法用 dayofweek 功能做到这一点
-
或者你对分析函数有什么建议吗?