Smart SQL Query用于计算多列的总和

时间:2018-05-29 21:05:04

标签: sql select

我有50个银行账户: B1,B2,B3,... B50 。他们每个人都有一个最后修改日期。 D1,D2,D3,...,D50 。 我想要一个查询,可以在每个帐户最后修改日期之后向我提供所有这些银行帐户的总和。 这个查询的天真版本是:

select sum(balance)
from ((select balance from accounts where address=B1 and lastModifiedDate>D1)
union
(select balance from accounts where address=B2 and lastModifiedDate>D2)....  
(select balance from accounts where address=B50 and lastModifiedDate>D50))

编写此查询的更聪明的方法是什么?

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

select sum(case when address=B1 and lastModifiedDate>D1 then balance else null end)....
相关问题