2

我正在尝试编写一个查询来计算结果集中的各种分组。我可以看到如何使用光标进行操作,但是是否也可以使用 Partition By 命令?基本上,任何比游标性能更好的东西。

数据:

Name    Entity      Status
---------------------------
Bob     Car         Broken
Bob     Car         Broken
Bob     Car         Fixed
Bob     Car         Stolen
Bob     Bike        Fixed
Bob     Bike        Fixed
Bob     Bike        Fixed
Bob     Bike        Stolen
Dave    Scooter     Broken
Dave    Car         Broken
Dave    Car         Fixed
Dave    Car         Stolen

报告:

Name    Entity      Broken  Fixed   Stolen
------------------------------------------
Bob     Car         2       1       1
Bob     Bike        0       3       1
Dave    Scooter     1       0       0
Dave    Car         1       1       1

谢谢

4

2 回答 2

4

COUNT 将在需要时忽略 NULL 以给出零

SELECT
   Name, Entity,
   COUNT(CASE WHEN Status ='Broken' THEN 1 ELSE NULL END) AS Broken,
   COUNT(CASE WHEN Status ='Fixed' THEN 1 ELSE NULL END) AS Fixed,
   COUNT(CASE WHEN Status ='Stolen' THEN 1 ELSE NULL END) AS Stolen
FROM table_name
GROUP BY Entity,Name
ORDER BY Name;
于 2013-06-18T10:03:13.667 回答
1

使用此查询:

SELECT  Name ,
    Entity ,
    [Broken] AS Broken ,
    [Fixed] AS Fixed ,
    [Stolen] AS Stolen
FROM    ( SELECT    Name ,
                Entity ,
                RTRIM(LTRIM(Statuse)) AS Statuse ,
                id
      FROM      [dbo].[table_name] AS TN
    ) AS T1_Temp PIVOT ( COUNT(id) FOR T1_Temp.Statuse IN ( [Broken],
                                                          [Fixed],
                                                          [Stolen] ) )  As PivotTable

我认为这个查询更快。

于 2013-09-06T12:19:19.173 回答