2017-03-03 2 views
1

Ich habe eine Tabelle A, die alle Rechnungen speichert (id 1) erhaltenen Zahlungen (ID 4) von Clients. Manchmal zahlen Kunden in 2-3 Raten. Ich möchte den Unterschied zwischen der Rechnungsstellung und der letzten Zahlung finden, die für die Rechnung gesammelt wurde. Meine Daten wie folgt aussiehtMindestdatum nach dem Anwenden des Filters

**a.cltid**|**A.Invnum**|A.Cash|A.Date | a.type| a.status 
70   |112   |-200 |2012-03-01|4  |P 
70   |112   |-500 |2012-03-12|4  |P 
90   |124   |-550 |2012-01-20|4  |P 
70   |112   |700 |2012-02-20|1  |p 
55   |101   |50 |2012-01-15|1  |d 
90   |124   |550 |2012-01-15|1  |P 

Ich betreibe

Select *, Datediff(dd,T.date,P.date) 
from (select a.cltid, a.invnumber,a.cash, min(a.date)date 
     from table.A as A 
where a.status<>'d' and a.type=1 
group by a.cltid, a.invnumber,a.cash)T 
join 
Select * 
from (select a.cltid, a.invnumber,a.cash, min(a.date)date 
     from table.A as A 
where a.status<>'d' and a.type=4 
group by a.cltid, a.invnumber,a.cash)P 
on 

T.invnumb=P.invnumber and T.cltid=P.cltid 

d = entfällt Wie kann ich es funktioniert? So ist es mir

70|112|-500|2012-03-12|4|P 70|112|700|2012-02-20|1|p|22 
90|124|-550|2012-01-20|4|P 90|124|550|2012-01-15|1|P|5 

Antwort

1

zeigt Ich glaube, Sie bedingte Aggregation benötigen:

select a.cltid, a.invnum, 
     max(case when a.type = 1 then a.date end) as issue_date, 
     max(case when a.type = 4 then a.date end) as last_payment_date, 
     datediff(day, 
       max(case when a.type = 1 then a.date end), 
       max(case when a.type = 4 then a.date end) 
       ) as diff 
from a 
where a.status <> 'd' 
group by a.cltid, a.invnum; 
+0

Ihnen danken. Ich habe es in meinem Kopf so komplex gemacht. Vielen Dank – Invisible

Verwandte Themen