首页 > 解决方案 > 如何将来自多个相似列的数据用作 SQL 中的行

问题描述

我有一个如下表:

项目名 1mth_presale_cost 2mth_presale_cost 1mth_postsale_cost 2mth_postsale_cost
1000 10.1 12.1 12.5 15.1
1001 20.2 15.2 25.2 17.3

我希望结果如下表:

项目名 1mth_cost 2mth_cost
1000 10.1 12.1
1000 12.5 15.1
1001 20.2 15.2
1001 25.2 17.3

我不想为此使用 UNION 。

标签: sqlsql-server

解决方案


首先将每一行转换为两组,然后应用条件 CASE 语句以获得所需的结果。

-- SQL Server
SELECT t.ItemName
     , CASE WHEN p.id = 1 THEN [1mth_presale_cost] ELSE [1mth_postsale_cost] END  "1mth_cost"
     , CASE WHEN p.id = 1 THEN [2mth_presale_cost] ELSE [2mth_postsale_cost] END  "2mth_cost"
FROM test t
CROSS JOIN (SELECT 1 id UNION SELECT 2 id) p
ORDER BY t.ItemName, p.id

请从网址https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=3e1fdaf829c39554941c068b0c8a3e04检查


推荐阅读