将特定的列取消透视成2个输出列

时间:2019-03-04 15:20:06

标签: sql sql-server sql-server-2014 unpivot

我有以下表源表A:

  [start1]     [end1]       [start2]     [end2]       [start3]      [end3]
  2019-01-01   2019-01-26   2019-01-27   2019-02-23   2019-02-24    2019-03-30  

我如何UNPIVOT来获得结果(理想情况下带有索引):

[index]  [start]     [end]       
1        2019-01-01  2019-01-26
2        2019-01-27  2019-02-23
3        2019-02-24  2019-03-30

2 个答案:

答案 0 :(得分:3)

您想要apply

select row_number() over (order by tt.start) as [index], tt.*
from table t cross apply 
     ( values ([start1], [end1]), ([start2], [end2]), . . .
     ) tt (start, end);

答案 1 :(得分:1)

请尝试以下操作:

SELECT p.[index],p.[start],p.[end]
FROM (
    SELECT TRY_CONVERT(INT,REPLACE(REPLACE(up.Param,'start',''),'end','')) AS [index]
        ,CASE WHEN up.Param LIKE 'start%' THEN 'start' ELSE 'end' END AS [Type]
        ,up.[Value]
    FROM [YourTableName] t
    UNPIVOT(Value FOR Param IN ([start1],[end1],[start2],[end2],[start3],[end3])) up
) a
PIVOT(MAX(a.[Value]) FOR [Type] IN ([start],[end])) p
;