在 ms sql 中优化带条件和不带条件的聚合
我想从一个列中得到一个总和,无论有没有条件。我现在拥有的代码是
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
Which Works,但看起来效率很低,更不用说丑陋了。该表相当大,因此欢迎进行一些优化。
我怎样才能以更好、更有效的方式写这个?
I would like to get a sum from a column, with and without a condition. The code I have now is
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
Which works, but seems very inefficient, not to mention ugly. the table is fairly large, so some optimisation would be welcome.
How can I write this in a better, more efficent way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你可以这样做:
但是,你想测试一下它是否更快。
I think you could do something like this:
However, you'd want to test to see if it was any faster.