我有以下看起来像这样的数据集:
ID Date PT Type
1 1/01/2018 Excellent
2 1/11/2018 Good
3 2/1/2018 Excellent
4 4/18/2018 Fair
5 7/23/2018 Bad
6 1/12/2019 Excellent
6 3/18/2019 Excellent
6 8/2/2019 Good
我想创建一个交叉表表,该表根据看起来像这样(或接近它)的年和月汇总数据
Year Month Excellent Good Fair Bad
2018 January 2 5 4 3
2018 February 7 0 2 9
....
我使用下面的stackoverflow链接来获取所需的代码框架,但是由于我需要基于Date
变量创建两个别名变量而遇到了问题。
我现在拥有的代码看起来像这样,但是我不确定如何完成它。
SELECT PT_TYPE ,
sum(case when PT_TYPE = 'Excellent' then 1 else 0 end) [Excellent],
sum(case when PT_TYPE = 'Good' then 1 else 0 end) [Good],
sum(case when PT_TYPE = 'Fair' then 1 else 0 end) [Fair]
from
(
select count(*) over(partition by Date)
from ED_TAT_MASTER
)
答案 0 :(得分:4)
subquery
,只需在year()
子句中使用month()
和group by
并进行聚合:
SELECT YEAR(DATE), MONTH(DATE),
SUM(case when PT_TYPE = 'Excellent' then 1 else 0 end) [Excellent],
SUM(case when PT_TYPE = 'Good' then 1 else 0 end) [Good],
SUM(case when PT_TYPE = 'Fair' then 1 else 0 end) [Fair]
FROM ED_TAT_MASTER
GROUP BY YEAR(DATE), MONTH(DATE);