在ms sql中使用和不使用条件优化聚合

时间:2010-10-05 11:50:11

标签: sql optimization refactoring aggregate

我希望从列中获得一笔总和,无论是否有条件。我现在的代码是

SELECT regular.id, regular.sum as regularsum, special.sum as specialsum FROM 
(SELECT Sum(stuff) as sum, id FROM table
 WHERE commonCondition = true
 GROUP BY id) as regular
INNER JOIN 
(SELECT Sum(stuff) as sum, id FROM table
 Where commonCondition = true AND specialCondition = true
 GROUP BY id) as special
ON regular.id = special.id

哪个有效,但看起来非常低效,更不用说丑陋了。该表相当大,因此欢迎进行一些优化。

我怎样才能以更好,更有效的方式写出来?

1 个答案:

答案 0 :(得分:2)

我认为你可以这样做:

 SELECT 
    Sum(stuff) as regularsum, 
    sum(case when specialcondition=true then stuff else 0 end) as specialsum,
    id FROM table
 WHERE commonCondition = true
 GROUP BY id

但是,你想测试它是否更快。