SQL Server中需要数据透视功能帮助

时间:2017-01-31 07:38:04

标签: sql sql-server sql-server-2008 pivot pivot-table

我正在尝试使用以下信息创建数据透视表:

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

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分: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