2017-05-17 21 views
1

我有一個Postgres 9.5 DB像下面3個表,PostgreSQL的 - 組過濾了具體的行

threshold

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

customers - 每個客戶都有threshold_idthreshold的表

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 

我想查詢它,並通過提升charges.id列的順序返回特定post_datesum(amount) == threshold_amount

的結果集看起來像下面,

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

我已經試過sum(amount)group by customer_id並調用存儲過程從select子句中分離並通過amount,post_datethreshold_amount然後創建一個臨時表,並插入post_date如果上述條件匹配,然後再次訪問該臨時表,但它似乎是無效的,所以我想知道是否有其他解決方案或我可以在查詢中做到這一點?

謝謝

回答

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; 
+0

好吧,我會檢查它 –

+0

在這裏,在這種情況下POST_DATE可以是任何順序,以便爲了通過應該是ch.id.對!! –

+0

@NileshWani。 。 。您可以根據需要進行訂購。日期對我有意義。 –

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 
+0

給出錯誤:集合函數不允許在WHERE –