将SQL数据以一种格式转换为另一种格式

时间:2016-12-01 13:37:45

标签: sql sql-server

拥有以下格式的数据: -

valleyname value

Valley 1   0  
Valley 1   22

Valley 1   74

Valley 1   116  
Valley 1   0  
Valley 1   182  
Valley 1   184  
Valley 2    30  
Valley 3    30  
Valley 4    80  
Valley 5    60 

想要将其转换为以下格式: -

Valley 1        Valley 2    Valley 3    Valley 4    Valley 5

22                   30        30         80        60

74                 NULL       NULL       NULL       NULL

116                NULL       NULL       NULL       NULL

182                NULL       NULL       NULL       NULL

184                NULL       NULL       NULL       NULL

我该如何处理这项任务?

提前致谢。

2 个答案:

答案 0 :(得分:1)

这很棘手,因为您没有可以转动的列。一种方法使用row_number()和条件聚合:

select max(case when valeyname = 'Valley 1' then value end) as valley_1,
       max(case when valeyname = 'Valley 2' then value end) as valley_2,
       max(case when valeyname = 'Valley 3' then value end) as valley_3,
       max(case when valeyname = 'Valley 4' then value end) as valley_4,
       max(case when valeyname = 'Valley 5' then value end) as valley_5       
from (select t.*,
             row_number() over (partition by valleyname order by valleyname) as seqnum
      from t
     ) t
group by seqnum;

答案 1 :(得分:1)

您可以使用pivot来执行此操作:

DECLARE @valleys TABLE
    (
      [valleyname] VARCHAR(20) ,
      [value] INT
    );
INSERT  INTO @valleys
        ( valleyname, value )
VALUES  ( 'Valley 1', 0 ),
        ( 'Valley 1', 22 ),
        ( 'Valley 1', 74 ),
        ( 'Valley 1', 116 ),
        ( 'Valley 1', 0 ),
        ( 'Valley 1', 182 ),
        ( 'Valley 1', 184 ),
        ( 'Valley 2', 30 ),
        ( 'Valley 3', 30 ),
        ( 'Valley 4', 80 ),
        ( 'Valley 5', 60 );

WITH    vset ( valleyname, vnum, [value] )
          AS ( SELECT   valleyname ,
                        ROW_NUMBER() OVER ( PARTITION BY valleyname ORDER BY valleyname ) ,
                        [value] value
               FROM     @valleys
               WHERE    [value] <> 0
             )
    SELECT  *
    FROM    vset PIVOT ( MAX([value]) FOR vnum IN ( [1], [2], [3], [4], [5] ) ) pvt;