如何Pivot/Unpivot没有列名的数据,只有1行数据

How to Pivot/Unpivot data without column names, and only 1 row of data

我有一个数据集,它来自查询。解释这个问题的最简单方法是向您展示数据集的样子。

假设我创建了这个 Table,并插入了数据。

Create table #tempTable2 (Locaiton1 decimal(10,2), Location2 Decimal(10,2), Location3 decimal(10,2), Location4 decimal(10,2),
Location5 Decimal(10,2))
Insert into #temptable2 Values ('22.4','33.4', '12.4', '95.94','23.40')
select * 
from #tempTable2

当你select数据时,你的输出是:

Location1 |  Location2 | Location3 |  Location4| Location5
   22.4   |  33.4      | 12.4      |  95.94    | 23.40

我想做的是像这样显示数据:

Location  | Amount
Location1 | 22.4
Location2 | 33.4
Location3 | 12.4
Location4 | 95.94
Location5 | 23.40

如何在 SQL 服务器中完成此操作?

我不得不说你的 table 的结构很糟糕,它的结构应该像你想要的结果一样,直接来自 get-go 两列。我也知道这个 table 可能已经存在并且您无法控制架构。

要获得所需的结果,您可以使用 UNION:

SELECT 'Location1' as Location, Location1 as Amount FROM yourtable
UNION ALL
SELECT 'Location2' as Location, Location2 as Amount FROM yourtable
UNION ALL
SELECT 'Location3' as Location, Location3 as Amount FROM yourtable
UNION ALL
SELECT 'Location4' as Location, Location4 as Amount FROM yourtable
UNION ALL
SELECT 'Location5' as Location, Location5 as Amount FROM yourtable

修复#tempTable2 定义中的拼写错误,使用 CROSS APPLY 使您不必扫描 table N 次,每个 Location 列扫描一次:

SELECT y.Location, y.Amount
FROM #tempTable2 AS t2
CROSS APPLY (VALUES
  ('Location1', Location1),
  ('Location2', Location2),
  ('Location3', Location3),
  ('Location4', Location4),
  ('Location5', Location5)
) AS y (Location, Amount);

输出:

Location Amount
Location1 22.40
Location2 33.40
Location3 12.40
Location4 95.94
Location5 23.40