【问题标题】:SQL - Aggregate dates from different columns into Month/Year tableSQL - 将不同列中的日期聚合到月/年表中
【发布时间】:2020-06-08 19:45:48
【问题描述】:
所以我有一个“订单”表,其中列出了每个订单的“订购”和“发货”日期。
这些是定制产品,需要 1 周才能完成订单。
这很能代表我的桌子:
我想将其汇总到一个表格中,以便我可以查看在运行报告时指定的日期范围内每个月订购和发货的订单数量,并且我希望月份和年份自动填充而无需我硬编码每个月和年:
使用 SQL 执行此操作的最佳方法是什么?
我最终希望将汇总表放入 SSRS 报告中,以便您可以在需要时每年展开/折叠。
【问题讨论】:
标签:
sql
pivot
aggregate-functions
【解决方案1】:
众所周知,日期/时间函数依赖于数据库。不过,这是一种典型的方法:
select yyyy, mm, sum(num_ordered), sum(num_shipped)
from ((select year(ordered) as yyyy, month(ordered) as mm, count(*) as num_ordered, 0 as num_shipped
from orders
group by year(ordered), month(ordered)
) union all
(select year(shipped) as yyyy, month(shipped) as mm, 0 count(*) as num_shipped
from orders
group by year(shipped), month(shipped)
)
) ym
group by yyyy, mm;