使用sql返回enddate,其中累计的费用列数小于1100

时间:2014-10-31 18:33:15

标签: sql

end date    fee
-----------------
05-Sep-14   700
12-Sep-14   200
19-Sep-14   100
26-Sep-14   300
03-Oct-14   400

在此处显示的表格中,我需要使用SQL返回enddate,其中累计费用列数小于1100.

示例:

19-Sep-14 (700 + 200 + 100 < 1100)

2 个答案:

答案 0 :(得分:1)

SELECT TOP 1
    t1.enddate, 
    t1.fee, 
    SUM(t2.fee) as cumulative_sum
FROM test t1
INNER JOIN tableName t2 on t1.enddate >= t2.enddate
GROUP BY t1.enddate, t1.fee
HAVING SUM(t2.fee) < 1100
ORDER BY t1.enddate DESC

答案 1 :(得分:1)

数据样本

create view fees
as
select cast('05-Sep-14' as date) as end_date,   700 as fee
union all select '12-Sep-14',   200
union all select '19-Sep-14',   100
union all select '26-Sep-14',   300
union all select '03-Oct-14',   400

解决方案

SELECT TOP 1
    a.end_date,     
    SUM(b.fee) as cumulative
FROM fees a CROSS JOIN fees b
WHERE a.end_date >= b.end_date
GROUP BY a.end_date
HAVING SUM(b.fee) < 1100
ORDER BY end_date desc