这是原始表格,其中包含带有日期和计数的ID列表。我需要对计数进行透视,然后将日期当前日期getdate()
分解为桌子上的日期,该日期按0-5天,10-15 ....
Type Date Volume
-------- ----- ------
primary mar 10,2019 1
Sub mar 8,2019 2
Pending mar 13,2019 3
XX mar 4,2019 5
我想要的是显示结果,如下所示:
TYPE 0-5 Days 5-10 Days 11-15 Days 16-20 Days 21-30 Days Total
primary 1 4 1 6 1 13
sub 3 5 5 7 0 20
pending 1 1 1 1 1 5
5 10 7 14 2 38
答案 0 :(得分:1)
我假设您正在寻找将日期与当前日期进行比较的卷的有条件总和。并具有汇总功能。
然后这样:
SELECT Type,
SUM(CASE WHEN DATEDIFF(day,[Date],GetDate()) BETWEEN 0 AND 5 THEN Volume ELSE 0 END) AS [0-5 Days],
SUM(CASE WHEN DATEDIFF(day,[Date],GetDate()) BETWEEN 6 AND 10 THEN Volume ELSE 0 END) AS [6-10 Days],
SUM(CASE WHEN DATEDIFF(day,[Date],GetDate()) BETWEEN 11 AND 15 THEN Volume ELSE 0 END) AS [11-15 Days],
SUM(CASE WHEN DATEDIFF(day,[Date],GetDate()) BETWEEN 16 AND 20 THEN Volume ELSE 0 END) AS [16-20 Days],
SUM(CASE WHEN DATEDIFF(day,[Date],GetDate()) BETWEEN 21 AND 30 THEN Volume ELSE 0 END) AS [21-30 Days],
SUM(Volume) AS Total
FROM yourtable
WHERE [Date] >= CAST(GetDate()-30 AS DATE)
GROUP BY Type WITH ROLLUP