2017-03-03 31 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