2017-05-23 103 views
-1

我正在嘗試轉置數據。列數不固定(即選定的ShiftNames不固定)。這是我的輸入數據。SQL Server:將行轉置爲列

Date_time ShiftName  Consumption 
28-07-2016 Shift 1  20 
28-07-2016 Shift 2  21 
28-07-2016 Shift 3  22 
29-07-2016 Shift 1  30 
29-07-2016 Shift 2  31 
29-07-2016 Shift 3  32 
30-07-2016 Shift 1  40 
30-07-2016 Shift 2  41 
30-07-2016 Shift 3  42 

和輸出會像高級此

Shift 1  Shift 2 Shift 3 Date_Time 
20   21   23  28-07-2016 
30   31   32  29-07-2016 
40   41   42  30-07-2016 

感謝。

+3

您是否嘗試過的東西了嗎? Google的「數據透視查詢SQL」適用於初學者。 –

回答

2

你可以用一個數據透視表做到這一點。下面是一個例子:

測試數據:

DECLARE @temp TABLE(Date_time varchar(100), ShiftName VARCHAR(100), Consumption INT) 

INSERT INTO @temp 
VALUES 
('28-07-2016','Shift 1',20), 
('28-07-2016','Shift 2',21), 
('28-07-2016','Shift 3',22), 
('29-07-2016','Shift 1',30), 
('29-07-2016','Shift 2',31), 
('29-07-2016','Shift 3',32), 
('30-07-2016','Shift 1',40), 
('30-07-2016','Shift 2',41), 
('30-07-2016','Shift 3',42) 

支點:

SELECT 
    * 
FROM 
(
    SELECT 
     Date_time, 
     ShiftName, 
     Consumption 
    FROM 
     @temp 
) AS sourceTable 
PIVOT 
(
    SUM(Consumption) 
    FOR ShiftName IN ([Shift 1],[Shift 2],[Shift 3]) 
) AS pvt 

結果:

Date_time  Shift 1 Shift 2 Shift 3 
28-07-2016 20  21  22 
29-07-2016 30  31  32 
30-07-2016 40  41  42 

參考:

+0

謝謝..它工作正常。 – Milind

0

由於shiftName是動態的,使用這個動態查詢

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) 
SELECT 
@cols = STUFF((SELECT distinct ',' + QUOTENAME(ShiftName) 
FROM 
#temp  
FOR XML PATH(''), TYPE 
).value('.', 'NVARCHAR(MAX)'),1,1,'') 

SET @query = 'SELECT * FROM 
(
    SELECT * FROM #temp 
) x 
PIVOT 
( 
    Sum(consumption) 
FOR ShiftName IN (' + @cols + ') 
) p ' 

EXECUTE(@query);