我有一个返回 1 行的查询:
SELECT fy.Id ,
fy.FirstStart ,
fy.SecondStart ,
fy.ThirdStart ,
fy.FourthStart
FROM dbo.FiscalYears fy
WHERE [Year] = 2017
这是结果:
| Id | FirstStart | SecondStart | ThirdStart | FourthStart |
|----|------------|-------------|------------|-------------|
| 5 | 2016-04-03 | 2016-07-03 | 2016-10-02 | 2017-01-01 |
我想把它变成:
| Name | Date |
|-------------|------------|
| FirstStart | 2016-04-03 |
| SecondStart | 2016-07-03 |
| ThirdStart | 2016-10-02 |
| FourthStart | 2017-01-01 |
我已经查看了与此类似的其他问题,这些问题在子查询中使用了 PIVOT,但我无法弄清楚。任何帮助表示赞赏。
最佳答案
使用UNPIVOT
:
SELECT Id, Name, Date
FROM
(
SELECT Id, FirstStart, SecondStart, ThirdStart, FourthStart
FROM dbo.FiscalYears
) fy
UNPIVOT
(Date FOR Name IN (FirstStart, SecondStart, ThirdStart, FourthStart)) AS t
关于t-sql - 使用 SQL Server 2012+ 和 T-SQL 将列转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470947/