将特定列反透视为 2 个输出列

Unpivot specific columns into 2 output columns

我有以下 table 来源 table 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

你想要 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);

请试试这个:

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
;