我有这个数据集:
DatasetMonthYear
Month Year Id Person_Id Name
-----------------------------------------------------
1 2007 855 5987456 John Slow
2 2007 850 5987456 John Slow
1 2007 254 5987456 John Slow
2 2008 987 5987456 John Slow
1 2007 456 5454543 Mary Jane
1 2007 454 5454543 Mary Jane
2 2008 554 5454543 Mary Jane
我需要逐个分组或统计一行,Id和Person_Id,但将该事件计为一个,所以我进行此查询。
select pv.Person_Id, pv.Name, pv.Year,
(CASE [1] when 0 THEN 0 else 1 end) as January,
(CASE [2] when 0 THEN 0 else 1 end) as Februry
from DatasetMonthYear as P
pivot ( count(Id) for
Month in ([1], [2]) ) as pv
结果是这个数据集:
Person_Id Name Year January February
------------------------------------------------------
5987456 John Snow 2007 1 0
5987456 John Snow 2007 0 1
5987456 John Snow 2008 0 1
5454543 Mary Jane 2007 1 0
5454543 Mary Jane 2008 0 1
现在我需要每年一个Person_Id的总和,所以我尝试添加另一个支点,如下所示。
select Person_Id,Name, [2007], [2008]
from (select pv.Person_Id,pv.Name, Year, (CASE [1] when 0 THEN 0 else 1 end) as January,
(CASE [2] when 0 THEN 0 else 1 end) as February
from DatasetMonthYear as P
pivot ( count(Id) for
Month in ([1], [2]) ) as pv) as resulset
pivot( sum() for Year in ([2007],[2008]) ) as apv
这是我被困的地方。我需要按Person_ID进行分组,每个月的总和(1月+ Februry + ... +等)和年份的数据
我想要的结果:
2007 2008 Person_Id Name
2 1 5987456 John Snow
1 1 5454543 Mary Jane
答案 0 :(得分:1)
我认为你不需要两个Pivot,你可以使用一个Pivot获得你想要的结果,见下文
select * from
(
select DISTINCT Person_Id, name, Year, Month From DatasetMonthYear
) Src
Pivot
(
Count(Month) For Year In ([2007],[2008])
) Pvt