PostgreSQL - 通过过滤掉特定行

时间:2017-05-17 10:48:26

标签: sql postgresql group-by

我在Postgres 9.5 DB中有3个表,如下所示,

threshold

id    threshold_amount
----------------------
111   100
112   200
113   80

customers - 每个客户都有threshold_id threshold

id   customer_name threshold_id
--------------------------------
313  abc           111
314  xyz           112
315  pqr           113

charges - 每位客户收取费用,因此此表格为customer_id

id    customer_id  amount  post_date     
------------------------------------
211   313         50       4/1/2017
212   313         50       4/30/2017 
213   313         50       5/15/2017
214   314         100      3/1/2017
215   314         50       3/21/2017
216   314         50       4/21/2017
217   314         100      5/1/2017
218   315         80       5/5/2017

我想查询它并按post_date列的升序返回具有sum( amount ) == threshold_amount的特定charges.id

结果集如下所示,

customer_id   post_date
-----------------------
313           4/30/2017           
314           4/21/2017
315           5/5/2017

我已使用sum( amount )尝试group by customer_id并将该存储过程与select子句分开,并传递amountpost_date和{{1}然后创建一个临时表并插入threshold_amount如果上述条件匹配,然后再次访问该临时表但似乎无效,所以我想知道是否有其他解决方案或我可以在查询中执行?

由于

2 个答案:

答案 0 :(得分:1)

您的问题是询问阈值的完全匹配。这基本上是一个累积总和:

select cct.*
from (select ch.customer_id, ch.amount,
             sum(ch.amount) over (partition by ch.customer_id order by post_date) as running_amount,
             t.threshold_amount
      from charges ch join
           customers c
           on ch.customer_id = c.id join
           threshholds t
           on c.threshold_id = t.id
     ) cct
where running_amount = threshold_amount;

答案 1 :(得分:0)

试试这个:

select
c.customer_id,
c.post_date
from charges c
join customers cu on cu.id = c.customer_id
join threshold t on t.id = cu.threshold_id
where (select sum(cc.amount) from charges cc where cc.id <= c.id 
and cc.customer_id = c.customer_id) = t.threshold_amount