SQL按行分隔列值(pivot)

时间:2013-08-23 07:17:28

标签: sql sql-server join pivot

表1

| MODULE | COUNT | YEAR |
-------------------------
|     M1 |    12 | 2011 |
|     M1 |    43 | 2012 |
|     M2 |     5 | 2011 |
|     M3 |    24 | 2011 |
|     M4 |    22 | 2011 |
|     M4 |    11 | 2012 |
|     M5 |    10 | 2012 |

我想像这样显示

| MODULE |   2011 |   2012 |
----------------------------
|     M1 |     12 |     43 |
|     M2 |      5 |     -  |
|     M3 |     24 |     -  |
|     M4 |     22 |     11 |
|     M5 |     -  |     10 |

4 个答案:

答案 0 :(得分:1)

可以使用PIVOT查询完成此操作。或者以下:

select Module,
       SUM(CASE WHEN Year='2011' then Count ELSE 0 END) as [2011],
       SUM(CASE WHEN Year='2012' then Count ELSE 0 END) as [2012]
FROM T
GROUP BY Module

SQL Fiddle demo

答案 1 :(得分:1)

您可以使用PIVOT

SELECT 
  Module,
  [2011], [2012]
FROM
  (
  SELECT 
    *  
  FROM Table1
  ) AS SourceTable
PIVOT
  (
  SUM([Count])
  FOR [Year] IN ([2011], [2012])
  ) AS PivotTable;

如果您没有受限Year

,也可以使用此动态查询
DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) 
                    from Table1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @query = 'SELECT Module,' + @cols + ' 
             FROM
             (
                Select *
                FROM Table1
             ) dta
             PIVOT
             (
                SUM([Count])
                FOR [Year] IN (' + @cols + ')
             ) pvt '
EXECUTE(@query);

结果:

| MODULE |   2011 |   2012 |
----------------------------
|     M1 |     12 |     43 |
|     M2 |      5 | (null) |
|     M3 |     24 | (null) |
|     M4 |     22 |     11 |
|     M5 | (null) |     10 |

请参阅this SQLFiddle


更新

您还可以使用此替代动态方法:( @valex给出的查询动态)

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT distinct ',' 
                      + ' SUM(CASE WHEN YEAR= ''' + CAST(Year AS varchar(50))
                      + ''' THEN [COUNT] ELSE ''-'' END) AS ' + QUOTENAME([Year])
                    from Table1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


SET @query = 'SELECT Module, ' + @cols + ' 
             FROM Table1 GROUP BY Module'
EXECUTE(@query);

请参阅this SQLFiddle

答案 2 :(得分:0)

我认为您需要查看关系运算符PIVOT。

Using PIVOT and UNPIVOT

SELECT Module, 
[2011], [2012]
FROM T
PIVOT (SUM(Count) FOR Year IN ([2011], [2012])) AS PivotTable;

答案 3 :(得分:0)

SELECT *
FROM   Tablename
PIVOT  (
       AVG([Count] FOR [Year] IN (2011, 2012, 2013)) AS AvgCount
)