如何在SQL查询中将多列设置为行

时间:2019-06-11 17:45:05

标签: sql-server pivot unpivot

我想使用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

1 个答案:

答案 0 :(得分:1)

  • 首先,您需要取消枢纽分析表,请注意,您需要将数据转换为相同的类型,因为每个数据都将进入同一列。
  • 然后您就可以转向想要的结果。
  • 如果需要,可以将其转换回原始数据类型。

SQL FIDDLE

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以查看中间结果。