Postgresql-每日部分总计,一次查询总计

时间:2019-06-26 12:57:58

标签: postgresql

我有一张带有不同时间戳的不同交易表:

表:交易

Recipient   Amount    Date
--------------------------------------------------
Bob         52        2019-04-21 11:06:32
Jack        12        2019-06-26 12:08:11
Jill        50        2019-04-19 24:50:26
Bob         90        2019-03-20 16:34:35
Jack        81        2019-03-25 12:26:54
Jenny       53        2019-04-20 09:07:02
Jenny       5         2019-03-29 06:15:35

现在,我想获得杰克今天和整个交易的全部信息:

结果

Person   Amount_Today   Amount_Overall             
-----------------------------------------------
Jack     12             93      

在PostgreSQL中最有效的方法是什么?目前,我运行两个查询-该查询用于Amount_Today:

select Recipient, sum(Amount)
from Transactions
where Recipient = 'Jack'
and created_at > NOW() - INTERVAL '1 day' 

但这似乎不是正确的方法。

1 个答案:

答案 0 :(得分:3)

您可以使用filter子句:

select Recipient, 
       sum(Amount) as Amount_Overall,
       sum(Amount) FILTER (WHERE created_at > NOW() - INTERVAL '1 day') as Amount_Today
from Transactions
where Recipient = 'Jack'
GROUP BY recipient;

您可能已经意识到了这一点,但是now()-间隔“ 1天”并不是今天真正的时间,而是最近的24小时。如果只想今天,可以使用date_trunc。