如果你的意思是你已經有一個產生設置像下面
DueDate | DateFrom | DateTo | AmountDue | AmountPaid | DueToDate | PaidToDate
20120301 | 20120201 | 20120229 | 100.00 | 50.00 | 100.00 | 50.00
20120401 | 20120301 | 20120331 | 100.00 | 50.00 | 200.00 | 100.00
20120501 | 20120401 | 20120430 | 100.00 | 50.00 | 300.00 | 150.00
20120601 | 20120501 | 20120531 | 100.00 | 50.00 | 400.00 | 200.00
結果的查詢,然後這裏有前視每月AmountDue是否是恆定的兩種方式。如果是,那麼你可以使用
select *
from QueryResult
where DueToDate - PaidToDate >= 2 * AmountPaid;
如果不是恆定的,那麼你可以使用SQL Server 2012 LAG()從現有行添加AmountPaid到當前
;WITH Lagged AS (
select *, PriorAmount = LAG(AmountPaid, 1, 0) OVER (order by DueDate)
from QueryResult
)
select *
from Lagged
where DueToDate - PaidToDate >= AmountPaid + PriorAmount;
或者只需在原始查詢的另一列中保留一個正在運行的總數,例如
DueDate | DateFrom | DateTo | AmountDue | AmountPaid | DueToDate | PaidToDate | TwoPeriods
20120301 | 20120201 | 20120229 | 100.00 | 50.00 | 100.00 | 50.00 | 100.00
20120401 | 20120301 | 20120331 | 100.00 | 50.00 | 200.00 | 100.00 | 200.00
20120501 | 20120401 | 20120430 | 100.00 | 50.00 | 300.00 | 150.00 | 200.00
20120601 | 20120501 | 20120531 | 100.00 | 50.00 | 400.00 | 200.00 | 200.00
哪個版本的SQL Server 2012的? – RichardTheKiwi 2013-04-20 11:46:44
嗨。謝謝 – 2013-04-20 14:42:02