SQL查询报告

时间:2012-11-20 13:40:16

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

我正在编写汇总报告,到目前为止我已经掌握了数据,但我不确定如何从这里开始。我接受SQL但我的技能有限

我在临时表中有以下内容

ID   Count  Action
2   23      Installed
2   12      Uninstalled
2   36      Unchanged
3   12      Installed
3   25      Unchanged
4   35      Installed
4   25      Unchanged

我想将其转换为此格式

ID  Installed   Uninstalled Unchanged
2   23          12          36
3   12          0           36
4   35          0           25

我不知道该去哪里,甚至不知道如何开始实现这个目标,也无法找到任何指向正确方向的东西(我确定它在某处)

任何帮助都是适当的

3 个答案:

答案 0 :(得分:1)

它被称为枢轴

Here's关于它的文档

语法是

SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,

    ...

    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the source query>
PIVOT
( 
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])

) AS <alias for the pivot table>

<optional ORDER BY clause>;

答案 1 :(得分:1)

试试这个:

SELECT
  ID, 
  MAX(CASE WHEN "Action" = 'Installed' THEN Count END) AS 'Installed',
  MAX(CASE WHEN "Action" = 'Uninstalled ' THEN Count END) AS 'Uninstalled',
  MAX(CASE WHEN "Action" = 'Unchanged' THEN Count END) AS 'Unchanged'
FROM Table
GROUP BY ID;

或者像这样使用SQL Server PIVOT表运算符:

SELECT *
FROM 
(
   SELECT * FROM table
)t
PIVOT
(
   MAX("Count") FOR "Action" IN([Installed], [Uninstalled], [Unchanged])
) p

SQL Fiddle Demo for both

但是,对于未知数量的Action s,您必须动态选择它们:

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Action) 
                    from Table1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');

SET @query = 'SELECT ID,  ' + @cols + ' from 
             (
                SELECT * FROM Table1
             ) x
             PIVOT 
             (
                MAX(count)
                FOR action IN (' + @cols + ')
             ) p ';

EXECUTE(@query);

SQL Fiddle Demo(Dynamic Version)

答案 2 :(得分:1)

枢轴很好,但有时很慢。没有一个尝试。

SELECT ID
    , SUM(CASE WHEN [Action] = 'Installed' THEN [Count] ELSE 0 END) AS Installed
    , SUM(CASE WHEN [Action] = 'Uninstalled' THEN [Count] ELSE 0 END) AS Uninstalled
    , SUM(CASE WHEN [Action] = 'Unchanged' THEN [Count] ELSE 0 END) AS Unchanged
FROM <table>
GROUP BY ID