我想使用SQL Server将列转换为行。我已经尝试过取消透视,但知识不足,只能使其成为一列
+--------+--------+---------+-----+-----+------+------------+
| UNit | excess | refuell | MBp | MCP | CPPF | DATE |
+--------+--------+---------+-----+-----+------+------------+
| TAPS-4 | 52 | test1 | 12 | 96 | 35 | 11/06/2019 |
| TAPS-3 | 52 | test1 | 13 | 96 | 35 | 11/06/2019 |
| TAPS-2 | 52 | test1 | 42 | 96 | 35 | 11/06/2019 |
| TAPS-1 | 52 | test1 | 18 | 96 | 35 | 11/06/2019 |
+--------+--------+---------+-----+-----+------+------------+
这是桌子
Values TAPS-4 TAPS-3 TAPS-2 TAPS-1
--------------------------------------
excess 52 52 52 52
MBp 12 13 42 18
MCP 96 96 96 96
CPPF 35 35 35 35
我想要这样,如下所示:
IN
答案 0 :(得分:1)
WITH unpvt as (
SELECT Unit, Attribute, Vals
FROM ( SELECT Unit,
cast(excess as nvarchar(100)) as excess,
cast(MBp as nvarchar(100)) as MBp,
cast(MCP as nvarchar(100)) as MCP,
cast(CPPF as nvarchar(100)) as CPPF
FROM Table1) as p
UNPIVOT
(Vals FOR Attribute in (excess, MBp, MCP, CPPF)
) as unpvt
)
SELECT Attribute, [TAPS-4], [TAPS-3], [TAPS-2], [TAPS-1]
FROM ( SELECT Unit, Attribute, Vals
FROM unpvt) p
PIVOT (
MAX(Vals) FOR Unit IN
([TAPS-4], [TAPS-3], [TAPS-2], [TAPS-1])
) pvt
输出
| Attribute | TAPS-4 | TAPS-3 | TAPS-2 | TAPS-1 |
|-----------|--------|--------|--------|--------|
| CPPF | 35 | 35 | 35 | 35 |
| excess | 52 | 52 | 52 | 52 |
| MBp | 12 | 13 | 42 | 18 |
| MCP | 96 | 96 | 96 | 96 |
注意::在sql小提琴中尝试SELECT * FROM unpvt
以查看中间结果。