2

表格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

4 回答 4

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 |

看到这个 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);

看到这个 SQLFiddle

于 2013-08-23T07:45:04.313 回答
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 演示

于 2013-08-23T07:27:11.533 回答
0

我认为您需要研究关系运算符 PIVOT。

使用 PIVOT 和 UNPIVOT

SELECT Module, 
[2011], [2012]
FROM T
PIVOT (SUM(Count) FOR Year IN ([2011], [2012])) AS PivotTable;
于 2013-08-23T07:30:02.923 回答
0
SELECT *
FROM   Tablename
PIVOT  (
       AVG([Count] FOR [Year] IN (2011, 2012, 2013)) AS AvgCount
)
于 2013-08-23T07:33:58.343 回答