【问题标题】:day of week function for week day aggregates工作日聚合的星期函数
【发布时间】: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 功能做到这一点
  • 或者你对分析函数有什么建议吗?

标签: sql db2


【解决方案1】:

您不能嵌套聚合函数。我想你只是想要:

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 daily_total else 0
           end) as dailyTotalWeek
from shoeTotals
where date_of_report >= current date - ( dayofweek(current date) - 1 ) days
group by employee;

【讨论】:

  • 好的,这是有道理的,但该列的记录似乎太多了。每个员工的表中还有其他类别,即使使用类别子句,它似乎也得到了所有人的总数
  • 问题似乎与您的原始查询有关。对于“今天”,即使您的 WHERE 子句显示为“date_of_report >= current_date”,您也可以使用条件“current_date - 1 天”(为什么是两天?)求和。在 Gordon Linoff 的回答中,这种差异只会变得很明显......
猜你喜欢
  • 1970-01-01
  • 2018-06-29
  • 2021-12-31
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2015-05-13
相关资源
最近更新 更多