2017-06-21 8 views
0

変換する方法として、テーブルのヘッダーとしてデータを変換し、ヘッダーとしてヘッダーを変換しますか?ここ行のデータを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   | 
+-------------------------+--------+--------+--------+--------+------------+ 

このSQLを実行してくださいでは、単一のクエリで(画像を参照)、特定のフォーマットにのMyDataを変換することができますか?

enter image description here

+0

SQL Serverでピボットを試したことがありますか? – scsimon

答えて

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

関連する問題