2017-03-03 30 views
1

我有一個表A,它存儲客戶發出的所有發票(id 1)收到的付款(id 4)。有時客戶分2-3次付款。我想在發票發票和上次爲發票收取的付款之間找到日期差異。我的數據是這樣的應用過濾器後的最短日期

**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 

我正在

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 =刪 我怎樣才能使它發揮作用?因此,它表明了我

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 

回答

1

我想你需要有條件聚集:

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

謝謝。我的頭腦真的很複雜。謝謝 – Invisible