如果您的意思是您已经有一个生成如下结果集的查询
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