2017-05-17 3 views
1

I 3 Tabellen in einer Postgres 9,5 DB haben wie untenPostgreSQL - Gruppe durch Filter aus bestimmten Zeilen

threshold

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

customers - jeder Kunde hat eine threshold_id von threshold Tabelle

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

charges - pro Kunde gibt es Gebühren, so dass diese Tabellehat

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 

Ich möchte es abzufragen und die spezifische post_date mit sum(amount) == threshold_amount Rückkehr im Auftrag von charges.id Spalte aufsteigend,

Die resultset aussehen wie unten,

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

Ich habe versucht sum(amount) mit group by customer_id und rufen Sie den einen separaten die gespeicherte Prozedur von Select-Klausel und übergeben Sie die amount, post_date und threshold_amount erstellt dann eine temporäre Tabelle und fügt post_date in es ein, wenn die obige Bedingung übereinstimmen und dann wieder auf diese temporäre Tabelle zugreifen, aber es scheint etwas nicht gültig, also möchte ich wissen, ob eine andere Lösung oder Kann ich es in Abfrage tun?

Danke

Antwort

1

Ihre Frage fragt nach einer genauen Übereinstimmung für den Schwellenwert. Dies ist im Grunde eine kumulative Summe:

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

Okay, ich werde es überprüfen –

+0

Hier in diesem Fall post_date jede Sequenz sein kann, so, um durch ch.id. sein sollte Recht!! –

+0

@NileshWani. . . Sie können bestellen, was auch immer angemessen ist. Das Datum ergab für mich Sinn. –

0

try this:

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

Giving ERROR: Aggregatfunktionen sind in WHERE nicht erlaubt –

Verwandte Themen