我有一张包含一些付款的表格,如下所示:
id | from | to | amount
--------------------------
1 | 125 | 135 | 2.4
2 | 123 | 134 | 1.7
3 | 124 | 138 | 4.8
4 | 118 | 119 | 3.9
5 | 56 | 254 | 23.5
...
我需要知道是否有一种方法可以进行SQL查询,告诉我是否有一系列连续的行,其总和达到某个值。例如,如果我想要值6.5,它将返回行2到3.如果我想要12.8,它将返回行1到4,依此类推。
我完全陷入困境,并希望得到一些帮助。
答案 0 :(得分:3)
我会按如下方式处理。首先,计算累积总和。然后,连续行具有特定总和的条件等同于说两个累积和之间的差等于该值。
with p as (
select p.*, sum(amount) over (order by id) as cumamount
from payments p
)
select
from p p1 join
p p2
on p1.id <= p2.id and
( p2.cumamount - p1.cumamount ) = 6.5;
注意:如果将amount
存储为浮点数,由于非常小的不准确性,这可能不起作用。如果amount
中有一个整数,那就没问题,但显然不是。定点表示应该没问题。
答案 1 :(得分:2)
;with numbers as (select number from master..spt_values where type='p' and number between 1 and (Select MAX(id) from yourtable)),
ranges as ( select n1.number as start, n2.number as finish from numbers n1 cross join numbers n2 where n1.number<=n2.number)
select yourtable.* from yourtable
inner join
(
select start, finish
from ranges
inner join yourtable on id between start and finish
group by start, finish
having SUM(amount)=12.8
) results
on yourtable.id between start and finish