问题描述
查找 ID 每年出现的次数并获得多列结果的最佳/最简单方法是什么。这似乎比我最初想象的要困难得多,除非我忽略了一些东西。
Table Example
ID Year
A 2010
B 2011
B 2012
C 2011
C 2011
C 2012
Desired Output
ID 2010_CNT 2011_CNT 2012_CNT
A 1 0 0
B 0 1 1
C 0 2 1
解决方法
WITH CTE(ID,YEAR)AS
(
SELECT 'A',2010 UNION ALL
SELECT 'B',2011 UNION ALL
SELECT 'B',2012 UNION ALL
SELECT 'C',2011 UNION ALL
SELECT 'C',2012
)
SELECT C.ID,SUM(CASE WHEN C.YEAR=2010 THEN 1 ELSE 0 END)AS Y_2010_CNT,SUM(CASE WHEN C.YEAR=2011 THEN 1 ELSE 0 END)AS Y_2011_CNT,SUM(CASE WHEN C.YEAR=2012 THEN 1 ELSE 0 END)AS Y_2012_CNT
FROM CTE AS C
GROUP BY C.ID
ORDER BY C.ID;
您可以使用条件聚合(示例如上。CTE 代表您提供的数据)
,如果您的值是固定的,您可以简单地使用条件聚合:
Select
id,sum(case when YEAR='2010' then 1 else 0 end) as Y_2010,sum(case when YEAR='2011' then 1 else 0 end) as Y_2011,sum(case when YEAR='2012' then 1 else 0 end) as Y_2012
from Example
group by id