t-sql - 使用 SQL Server 2012+ 和 T-SQL 将列转换为行

标签 t-sql sql-server-2012

我有一个返回 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/

相关文章:

c# - 让 WCF 服务知道 SQL Server Service Broker 消息已到达

sql - 拿走 EXISTS 但留在交换机中

sql-server - 使用文件流创建数据库时出错

sql - 顺序不同

sql - 工作日SQL查询

sql-server - 我希望在使用数据透视表和动态列名称的查询中使用 0 而不是空值

sql - select unique * 查询有多贵

sql - Binary_Checksum 与 HashBytes 函数

SQL:尝试在数据库的所有行中标记同一客户 ID 和订单号内的最早发货日期

sql - T-SQL 如何将多行合并为一行