Datediff 的日期在一列中,但仅显示与下一张发票相比的 datediff

Datediff with dates in one column but only showing datediff compared to the next invoice

这是为了了解客户花了多长时间支付账单。 datediff 需要是付款的下一张发票

如下例

ID  Type1         Amount        Date
--------------------------------------------------------------------
1    Invoice        38.16       2014-04-25     
1    Payment       -40.00       2014-03-23 
1    Invoice        40.86       2014-02-22 
1    Payment       -40.00       2014-02-21 
1    Invoice        42.21       2014-01-20


ID  Type1         Amount        Date             DATEDIFF 
---------------------------------------------------------
1    Invoice        38.16       2014-04-25     
1    Payment       -40.00       2014-03-23         29 
1    Invoice        40.86       2014-02-22 
1    Payment       -40.00       2014-02-21         32
1    Invoice        42.21       2014-01-20

这可以通过多种方式完成,一种选择是使用相关子查询为所有 item=payment 行获取带有 item=invoice 的前一行的日期:

select 
  id, type1, amount, date,
  datediff(day, 
    (select top 1 date 
     from table1 
     where date <= t.date 
     and type1= 'Invoice'
     and t.type1='Payment' 
     order by date desc), 
    date) as diff
from table1 t;

虽然这可能不是最有效的解决方案。

Sample SQL Fiddle

或者您可以使用具有相同效果的外部应用:http://www.sqlfiddle.com/#!6/b1e32/19