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

时间:2019-02-15 02:55:25

标签: sql sql-server

我有这样的数据

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

我有日历年和月份列,基于日历年和月份列,我需要创建多个年月列。

我可以先取消枢转,然后再进行枢转,以解决问题。但是,数据是如此之大,需要占用大量内存。性能很差。

1 个答案:

答案 0 :(得分:0)

不确定这是否是更好的方法,但是如果您不想执行透视/取消透视,也可以使用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