我希望从列中获得一笔总和,无论是否有条件。我现在的代码是
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
哪个有效,但看起来非常低效,更不用说丑陋了。该表相当大,因此欢迎进行一些优化。
我怎样才能以更好,更有效的方式写出来?
答案 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
但是,你想测试它是否更快。