Skip to content
Advertisement

One select instead two selects with where

I have two similar select like this:

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement