sqlserver如何把列转行
时间: 2023-07-27 14:13:18 浏览: 164
sqlserver使用UNPIVOT函数列转行
5星 · 资源好评率100%
在 SQL Server 中,可以使用 PIVOT 操作符将行数据转换为列数据,也可以使用 UNPIVOT 操作符将列数据转换为行数据。
举个例子,假设有以下的表:
```
CREATE TABLE Sales (
Year INT,
Quarter VARCHAR(10),
Amount MONEY
);
INSERT INTO Sales VALUES (2019, 'Q1', 1000);
INSERT INTO Sales VALUES (2019, 'Q2', 2000);
INSERT INTO Sales VALUES (2019, 'Q3', 3000);
INSERT INTO Sales VALUES (2019, 'Q4', 4000);
```
如果要将 Quarter 列转换为列名,可以使用 PIVOT 操作符:
```
SELECT Year, [Q1], [Q2], [Q3], [Q4]
FROM (
SELECT Year, Quarter, Amount
FROM Sales
) AS s
PIVOT (
SUM(Amount)
FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS p;
```
结果如下:
```
Year Q1 Q2 Q3 Q4
---- ----- ----- ----- -----
2019 1000.0 2000.0 3000.0 4000.0
```
如果要将列名转换为行数据,可以使用 UNPIVOT 操作符:
```
SELECT Year, Quarter, Amount
FROM (
SELECT Year, Q1, Q2, Q3, Q4
FROM (
SELECT Year, Quarter, Amount
FROM Sales
) AS s
PIVOT (
SUM(Amount)
FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS p
) AS u
UNPIVOT (
Amount FOR Quarter IN (Q1, Q2, Q3, Q4)
) AS up;
```
结果如下:
```
Year Quarter Amount
---- ------- ------
2019 Q1 1000.0
2019 Q2 2000.0
2019 Q3 3000.0
2019 Q4 4000.0
```
阅读全文