T-SQL帮助需要透视多个列

时间:2016-11-27 19:34:40

标签: sql-server tsql

我有一张桌子

City    Region      Zone    Passcode    SureveyBy   SureveyDone SureveyExpiry
Noida   Sector 62   East    1           ABC         Y           NULL
Noida   Sector 2    West    1           XYZ         N           6/10/2016
Delhi   CP          Cnt     10          ABC         N           10/10/2018
Delhi   KB          West    11          RST         Y           NULL

我需要这种格式的结果

Final Result

1 个答案:

答案 0 :(得分:0)

    DECLARE @col NVARCHAR(max),@sql NVARCHAR(max)
    SELECT  @col=ISNULL(@col+',[','[')+t.SureveyBy+']' FROM dbo.myTable AS t GROUP BY t.SureveyBy
    PRINT @col
    SET @sql='
       SELECT * FROM dbo.myTable
       PIVOT(MAX(SureveyDone) FOR SureveyBy IN ('+@col+')) p'
    EXEC(@sql)