需要解决方案表的转置

时间:2012-10-24 06:59:55

标签: sql sql-server-2008 c#-4.0 stored-procedures sql-server-2008-r2

我有一个名为Sample的表,看起来像。

enter image description here

我希望输出如下enter image description here

为此我构建了以下查询:

SELECT YEAR/MONTH, 1L,3L,4L,6L,8L
    FROM (
    SELECT PANEL, LAYERCOUNT, MONTHS
    FROM Sample) up
    PIVOT (SUM(Count) FOR CountOFL IN (1L,3L,4L,6L,8L)) AS pvt
    ORDER BY YEAR/MONTH

但它在“1”附近给出了错误语法错误。

enter image description here

1 个答案:

答案 0 :(得分:3)

对于您提供的表结构,此查询将返回CountOFL列上的透视表:

SELECT YEARMONTH, [1L],[3L],[4L],[6L],[8L]
FROM Sample
PIVOT (SUM(RecordCount) FOR CountOFL IN ([1L],[3L],[4L],[6L],[8L])) AS pvt
ORDER BY YEARMONTH

结果:

YEARMONTH                        1L          3L          4L          6L          8L
-------------------------------- ----------- ----------- ----------- ----------- -----------
Dec2011                          2           NULL        NULL        NULL        NULL
Jan2011                          NULL        4           NULL        NULL        NULL
Jul2012                          2           NULL        5           NULL        NULL
Jun2011                          NULL        NULL        NULL        NULL        1
Jun2012                          2           NULL        NULL        1           NULL
May2011                          NULL        5           NULL        NULL        NULL
Sep2012                          NULL        1           NULL        NULL        NULL

因此,您需要将PIVOTed列的值括在方括号中。