简体   繁体   English

一个 select 代替两个选择 where

[英]One select instead two selects with where

I have two similar select like this:我有两个类似的 select 像这样:

select sum(a)
from db
where date <= GETDATE()
group by id, id2

select sum(b)
from db
where date > GETDATE()
group by id, id2

I would like to simplify to one query, is it possible to write one select instead of this two?我想简化为一个查询,是否可以写一个 select 而不是这两个?

Yes.是的。 One method is two columns using conditional aggregation:一种方法是使用条件聚合的两列:

select id, id2, sum(case when date <= getdate() then a end),
       sum(case when date > getdate() then a end)
from db
group by id, id2;

Another is separate rows:另一个是单独的行:

select id, id2, (case when date <= getdate() then 'past' else 'future' end),
       sum(a)
from db
group by id, id2, (case when date <= getdate() then 'past' else 'future' end);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM