唯一记录的总和 - 比光标更好的性能

时间:2013-06-18 09:34:14

标签: performance sql-server-2008 tsql cursor

我正在尝试编写一个查询来计算结果集中的各种分组。 我可以看到如何使用游标,但是也可以使用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

由于

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

我认为这个查询更快。