不确定,但我觉得我错过了一些非常愚蠢的东西,我没有得到理想的结果。
查询非常简单
SELECT
CASE
WHEN
GROUPING(DATEPART(YEAR,[ENTRY DATE]))=1 THEN 'GRAND TOTAL'
WHEN
GROUPING(DATEPART(MONTH,[ENTRY DATE]))=1 THEN 'YEAR TOTAL'
WHEN
GROUPING([ENTRY DATE])=1
THEN
CONVERT(CHAR(4), [ENTRY DATE], 100) + CONVERT(CHAR(4), [ENTRY DATE], 120)
ELSE
CONVERT(VARCHAR,[ENTRY DATE])
END AS [ENTRY DATE],
COUNT([WORKTYPE]) AS [TOTAL VOLUME]
FROM Assessment.INDIVIDUAL_MAIN
WHERE [WorkType] IN ('QUERY','ASSESSMENT','DECLINE TO BRANCH')
GROUP BY ROLLUP(DATEPART(YEAR,[ENTRY DATE]),DATEPART(MONTH,[ENTRY DATE]),[ENTRY DATE])
所以我没有得到年度和月份的Concat,而是获得了空白
+-------------+-------+
| 2014-06-27 | 10757 |
+-------------+-------+
| 2014-06-28 | 2 |
| 2014-06-29 | 5 |
| 2014-06-30 | 16 |
| NULL | 10780 |
| 2014-07-27 | 1 |
| NULL | 1 |
| YEAR TOTAL | 10781 |
| 2015-06-27 | 1 |
| NULL | 1 |
| YEAR TOTAL | 1 |
| GRAND TOTAL | 10782 |
+-------------+-------+
当我简单地写'年'或'总计'时,它运作良好,但我想显示月份和年份值而不是名称。
我做错了什么?任何见解都会有很大的帮助。
修改1 :这是我的预期结果
+-------------+-------+
| 2014-06-27 | 10757 |
+-------------+-------+
| 2014-06-28 | 2 |
| 2014-06-29 | 5 |
| 2014-06-30 | 16 |
| 2014-06 | 10780 |
| 2014-07-27 | 1 |
| 2014-07 | 1 |
| 2014 | 10781 |
| 2015-06-27 | 1 |
| 2015-06 | 1 |
| 2015 | 1 |
| GRAND TOTAL | 10782 |
+-------------+-------+
答案 0 :(得分:0)
好的,我想你想要这个:
SELECT
CASE
WHEN GROUPING(DATEPART(YEAR,[ENTRY DATE]))=1
THEN DATENAME(yyyy,[ENTRY DATE])
WHEN GROUPING(DATEPART(MONTH,[ENTRY DATE]))=1
THEN DATENAME(yyyy,[ENTRY DATE])+' - '+DATENAME(mm,[ENTRY_DATE])
WHEN GROUPING([ENTRY DATE])=1
THEN CAST([ENTRY DATE] AS VARCHAR(50))
ELSE 'GRAND TOTAL'
END AS [ENTRY DATE],
COUNT([WORKTYPE]) AS [TOTAL VOLUME]
FROM Assessment.INDIVIDUAL_MAIN
WHERE [WorkType] IN ('QUERY','ASSESSMENT','DECLINE TO BRANCH')
GROUP BY ROLLUP(DATEPART(YEAR,[ENTRY DATE]),DATEPART(MONTH,[ENTRY DATE]),[ENTRY DATE])
答案 1 :(得分:0)
问题是ROLLUP
会在摘要行的[ENTRY DATE]
列中插入null。这就是为什么"年"和" GRANT" work,但引用[ENTRY DATE]
的任何内容都为null。非摘要行(GROUPING(x) = 0
) 能够显示[ENTRY DATE]
。
我不确定是否可以通过ROLLUP
获得所需的结果。你可能需要以不同的方式去做。
这是一个可能的解决方案。它计算各种聚合,然后将结果结合在一起。它有点混乱,但是......它有效(我认为)。
--Daily
select CONVERT(varchar, [Entry Date]) [ENTRY DATE],
COUNT(WORKTYPE) COUNT,
CONVERT(varchar, [Entry Date]) sort
from Assessment.INDIVIDUAL_MAIN
group by [ENTRY DATE]
union
--Monthly
select convert(varchar, DATEPART(year, [Entry Date])) + '-' + convert(varchar, DATEPART(month, [Entry Date])),
COUNT(WORKTYPE),
convert(varchar, DATEPART(year, [Entry Date])) + '-' + RIGHT('0' + RTRIM(MONTH([ENTRY DATE])), 2) + '-40'
from Assessment.INDIVIDUAL_MAIN
group by DATEPART(year, [Entry Date]), DATEPART(month, [Entry Date])
union
--Yearly
select convert(varchar, DATEPART(year, [Entry Date])),
COUNT(WORKTYPE),
convert(varchar, DATEPART(year, [Entry Date])) + '-20-40'
from Assessment.INDIVIDUAL_MAIN
group by DATEPART(year, [Entry Date])
union
--Grand Total
select 'GRAND TOTAL',
count(WorkType),
'9999'
from Assessment.INDIVIDUAL_MAIN
order by sort