如何根据月份列和日历年列将日历年列转换为多年到月的列

问题描述 投票:0回答:1

我有这样的数据

id   MoYear  CalenderYear   jan  feb mar dec
1    2017      2017          1    2  4   0 
1    2017      2018          1    0  6   10
2    2018      2018          80   5  8   22
3    2017      2018          30   12  0  3 

现在我想要这样的输出

id MOyear  jan_17 feb_17 mar_17 dec_17 jan_18 feb_18 mar_18 dec_18
1   2017    1      2     4        0     1      0       6     10
2   2018    null   null  null    null   80     5       8      22
3   2017    null   null  null    null   30     12      0      3

我有日历年份列和月份列,基于我需要制作多个年 - 月列的日历年和月份列。

我可以通过unpivoting来解决问题,然后再回到枢轴。但是,数据太大需要大量内存。表现非常糟糕。

sql sql-server
1个回答
0
投票

不确定这是否是更好的方法,但如果您不想使用pivot / unpivot,也可以使用case语句实现输出。

数据创建:

select 1 as ID,     2017 as MOYEar,  2017 as calenderyear, 1  as Jan,    2  as feb,  
4 as mar,    0  as dece into #temp union all 

 select 1 as ID,     2017 as MOYEar,  2018 as calenderyear, 1  as Jan,    0  as feb,  
 6 as mar,    10 as dece union all 
 select 2 as ID,     2018 as MOYEar,  2018 as calenderyear, 80 as Jan,    5  as feb,  
 8 as mar,    22 as dece union all 
 select 3 as ID,     2017 as MOYEar,  2018 as calenderyear, 30 as Jan,    12 as feb,  
 0 as mar,    3  as dece 

查询:

Select ID, MOYEar, max(case when calenderyear = '2017' then Jan else null end)  as Jan_17, 
max(case when calenderyear = '2017' then Feb else null end ) as Feb_17, 
max(case when calenderyear = '2017' then Mar else null end ) as Mar_17,
max(case when calenderyear = '2017' then Dece else null end)  as Dece_17, 
max(case when calenderyear = '2018' then Jan else null end ) as Jan_18, 
max(case when calenderyear = '2018' then Feb else null end ) as Feb_18, 
max(case when calenderyear = '2018' then Mar else null end ) as Mar_18,
max(case when calenderyear = '2018' then Dece else null end)  as Dece_18  from #temp 
Group by ID, MOYEar

输出:

ID  MOYEar  Jan_17  Feb_17  Mar_17  Dece_17 Jan_18  Feb_18  Mar_18  Dece_18
 1  2017    1         2       4       0       1         0   6      10
 3  2017    NULL    NULL    NULL    NULL     30        12   0       3
 2  2018    NULL    NULL    NULL    NULL     80         5   8      22
© www.soinside.com 2019 - 2024. All rights reserved.