在SELECT查询中防止重复的COUNT

时间:2012-03-08 00:07:57

标签: sql sql-server-2008 query-optimization

我有以下查询,您可以看到多个Count(CompetitorID)来电。这是性能问题,还是SQL Server 2008'缓存'Count?如果这是性能问题,是否可以存储Count以防止多次查找?

SELECT EventID,Count(CompetitorID) AS NumberRunners,
    CASE WHEN Count(CompetitorID)<5 THEN 1
         WHEN Count(CompetitorID)>=5 AND Count(CompetitorID)<=7 THEN 2
         ELSE 3 END AS NumberPlacings
FROM Comps
GROUP BY EventID Order By EventID;

2 个答案:

答案 0 :(得分:2)

获取一次值并随后尽可能使用它总是更好的做法。在您的情况下,您始终可以使用内部查询仅计算一次计数并从其值计算其他(派生)列,如下所示:

SELECT  EventID, NumberRunners,
        CASE WHEN NumberRunners <5 THEN 1
             WHEN NumberRunners >=5 AND NumberRunners <=7 THEN 2
             ELSE 3 
        END AS NumberPlacings
  FROM  (
            SELECT  EventID,
                    NumberRunners = Count(CompetitorID)
              FROM  Comps
            GROUP BY EventID
        ) t
Order By EventID;

答案 1 :(得分:0)

最简单的是:

SELECT EventID,Count(distinct CompetitorID)AS NumberRunners,     计数(不同的竞争者ID)&lt; 5那么1          当计数(不同的竞争者ID)&gt; = 5和计数(不同的竞争者ID)&lt; = 7那么2          ELSE 3 END作为NumberPlacings FROM Comps GROUP BY EventID按EventID排序;