2017-01-31 63 views
1

我嘗試使用下面的信息來創建數據透視表:旋轉功能幫助需要在SQL Server

SELECT 

    [RecordId], 
    [Source], 
    [Channel], 
    [Reading], 
    [DownloadDateTime] 

FROM [dbo].[tblDataSource] 

WHERE source = 'CSLF' 

把這個...

Source Channel   Reading DownloadDateTime 
CSLF Flare_Temp  1305  2016-04-26 22:18:40.290 
CSLF Flare_Flow  671  2016-04-26 22:18:41.600 
CSLF Methane   54.2  2016-04-26 22:18:42.960 

進入這個......

DownloadDateTime  FlareTemp  FlareFlow Methane 
2016-04-26   1305   671   54.2 

任何想法如何做到這一點?

+0

的可能的複製[SQL服務器:轉換行到列(http://stackoverflow.com/questions/16589282/sql-server-convert-rows-into-columns ) –

+0

[將行轉換爲SQL Server中'Pivot'的列的可能的副本](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – Eli

回答

2

這應該這樣做:

declare @t table ( [RecordId] int, 
        [Source] varchar(max), 
        [Channel] varchar(max), 
        [Reading] dec(18,2), 
        [DownloadDateTime] datetime) 

insert @t values (1, 'CSLF', 'Flare_Temp', 1305, '2016-04-26 22:18:40.290'), 
       (2, 'CSLF', 'Flare_Flow', 671, '2016-04-26 22:18:41.600'), 
       (3, 'CSLF', 'Methane', 54.2, '2016-04-26 22:18:42.960') 

SELECT DownloadDateTime, Flare_Temp, Flare_Flow, Methane 
FROM (
    SELECT [Source], [Channel], [Reading], CONVERT(CHAR(10), [DownloadDateTime], 121) as DownloadDateTime FROM @t WHERE [Source] = 'CSLF') d 
    pivot (SUM([Reading]) FOR [Channel] in (Flare_Temp, Flare_Flow, Methane)) piv