在SQL中查找三个连续值的最大总和?

时间:2015-04-23 09:26:20

标签: sql math azure-sql-database

说我有下表,名为revenues

id | revenue
------------
1  | 345
2  | 5673
3  | 0
4  | 45
5  | 4134
6  | 35
7  | 533
8  | 856
9  | 636
10 | 35

我想找到连续3个值的分组的最大总和。这就是我的意思:

ids  1 + 2 + 3   =>  345  + 5673 + 0    = 6018
ids  2 + 3 + 4   =>  5673 + 0    + 45   = 5718
ids  3 + 4 + 5   =>  0    + 45   + 4134 = 4179
ids  4 + 5 + 6   =>  45   + 4134 + 35   = 4214
ids  5 + 6 + 7   =>  4134 + 35   + 533  = 4702
ids  6 + 7 + 8   =>  35   + 533  + 856  = 1424
ids  7 + 8 + 9   =>  533  + 856  + 636  = 2025
ids  8 + 9 + 10  =>  856  + 636  + 35   = 1527

在这种情况下,我希望结果为6018,因为它是3个连续值的最大总和。我刚刚开始学习SQL,我唯一的其他语言是Java,而我能想到的就是使用for循环这是多么容易。有没有人知道如何开始编写这样的查询? SQL中是否存在类似的东西?

编辑:此外,是否可以扩展这样的东西?如果我有一个非常大的表并且我想找到一百个连续值的最大总和怎么办?

4 个答案:

答案 0 :(得分:3)

一种方法是使用两个联接来转到id+1id+2

SELECT max(t1.revenue+t2.revenue+t3.revenue)
FROM revenues t1
JOIN revenues t2 ON t1.id+1 = t2.id
JOIN revenues t3 ON t1.id+2 = t3.id

Demo.

答案 1 :(得分:3)

如果您的数据库支持lag()窗口函数,则可以在单个表扫描中检索结果:

select  max(rev3)
from    (
        select  revenue + 
                    lag(revenue) over (order by id) + 
                    lag(revenue, 2) over (order by id) as rev3
        from    revenues
        ) as SubQueryAlias

See it working at SQL Fiddle.

答案 2 :(得分:1)

with t as (
SELECT 1 as id, 345 as rev
UNION SELECT 2, 5673
UNION SELECT 3, 0
UNION SELECT 4, 45
UNION SELECT 5, 4134
UNION SELECT 6, 35
UNION SELECT 7, 533
UNION SELECT 8, 856
UNION SELECT 9, 636
UNION SELECT 10, 35)
SELECT TOP 1 id, SUM (rev) OVER (ORDER BY id ROWS 2 PRECEDING) r
FROM t
ORDER BY r desc;

在SQL Server 2012上提供答案3, 6018 *。

修改 查询确保我们只获得由3个收入组成的行:

with t as (
SELECT 1 as id, 345 as rev
UNION SELECT 2, 5673
UNION SELECT 3, 0
UNION SELECT 4, 45
UNION SELECT 5, 4134
UNION SELECT 6, 35
UNION SELECT 7, 533
UNION SELECT 8, 856
UNION SELECT 9, 636
UNION SELECT 10, 35)
SELECT TOP 1 id, r FROM 
  (SELECT  id
    , SUM (rev) OVER (ORDER BY id ROWS 2 PRECEDING) r
    , SUM (1) OVER (ORDER BY id ROWS 2 PRECEDING) cnt
  FROM t) as subslt
WHERE cnt = 3
ORDER BY r desc;

<小时/> *实际上3, 60182, 6018之间不确定。第二个/已编辑的查询是确定性的。

答案 3 :(得分:0)

这样的事情:

    select rev1,rev2,rev3, rev1.revenue+rev2.revenue+rev3.revenue total_rev from 
revenue rev1,
revenue rev2,
revenue rev3
where rev1.id1+1=rev2.id and rev2.id+1=rev3.id  and total_rev=
(select max(rev1.revenue+rev2.revenue+rev3.revenue) from
revenue rev1,
revenue rev2,
revenue rev3
where rev1.id1+1=rev2.id and rev2.id+1=rev3.id)