在SQL中将行数据转换为列

时间:2017-06-21 19:31:43

标签: sql-server pivot common-table-expression

我想将数据转换为表头,并将标题转换为行如何转换?

这里是示例数据请执行此SQL

DECLARE @MyData table( 
DateValue datetime,
Value1 int,
Value2 int,
Value3 int,
Value4 int,
ColumnData  Varchar(10)); 

INSERT INTO @MyData(DateValue,Value1,Value2,Value3,Value4,ColumnData)
VALUES('12/1/2016',10,20,30,40,'D1')

INSERT INTO @MyData(DateValue,Value1,Value2,Value3,Value4,ColumnData)
VALUES('12/1/2016',11,21,31,41,'D2')

INSERT INTO @MyData(DateValue,Value1,Value2,Value3,Value4,ColumnData)
VALUES('12/1/2016',12,22,32,42,'D3')

SELECT * FROM @MyData
+-------------------------+--------+--------+--------+--------+------------+
|        DateValue        | Value1 | Value2 | Value3 | Value4 | ColumnData |
+-------------------------+--------+--------+--------+--------+------------+
| 2016-12-01 00:00:00.000 |     10 |     20 |     30 |     40 | D1         |
| 2016-12-01 00:00:00.000 |     11 |     21 |     31 |     41 | D2         |
| 2016-12-01 00:00:00.000 |     12 |     22 |     32 |     42 | D3         |
+-------------------------+--------+--------+--------+--------+------------+

是否可以在单个查询中将MyData转换为特定格式(参考图像)?

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您的列和columnData是静态的,您可以单独转动每个值,然后使用UNION ALL创建一个表:

DECLARE @MyData table(DateValue datetime,   Value1 int, Value2 int, Value3 int, Value4 int, ColumnData  Varchar(10)); 
INSERT INTO @MyData(DateValue,Value1,Value2,Value3,Value4,ColumnData) VALUES('12/1/2016',10,20,30,40,'D1')
INSERT INTO @MyData(DateValue,Value1,Value2,Value3,Value4,ColumnData) VALUES('12/1/2016',11,21,31,41,'D2')
INSERT INTO @MyData(DateValue,Value1,Value2,Value3,Value4,ColumnData) VALUES('12/1/2016',12,22,32,42,'D3')

select 'Value1' as '12/1/2016',*, D1 + D2 + D3 as [Total] from(
        SELECT Value1, ColumnData FROM @MyData
    ) s
    pivot(
        sum(Value1) for ColumnData in (D1, D2 , D3)
    ) as pvt
union all
    select 'Value2' as '12/1/2016',*, D1 + D2 + D3 as [Total] from(
        SELECT Value2, ColumnData FROM @MyData
    ) s
    pivot(
        sum(Value2) for ColumnData in (D1, D2 , D3)
    ) as pvt
union all
    select 'Value3' as '12/1/2016',*, D1 + D2 + D3 as [Total] from(
        SELECT Value3, ColumnData FROM @MyData
    ) s
    pivot(
        sum(Value3) for ColumnData in (D1, D2 , D3)
    ) as pvt
union all
    select 'Value4' as '12/1/2016',*, D1 + D2 + D3 as [Total] from(
        SELECT Value4, ColumnData FROM @MyData
    ) s
    pivot(
        sum(Value4) for ColumnData in (D1, D2 , D3)
    ) as pvt

这是此查询的输出:

enter image description here