SQL Server查询用于查找4个连续值的总和

时间:2011-06-15 13:55:03

标签: sql-server-2005

有人可以帮助我找到4个连续值的总和,即最后4个值的滚动总和。

像:

VALUE   SUM
1   NULL
2   NULL
3   NULL
4   10
5   14
6   18
7   22
8   26
9   30
10  34
11  38
12  42
13  46
14  50
15  54
16  58
17  62
18  66
19  70
20  74
21  78
22  82
23  86
24  90
25  94
26  98
27  102
28  106
29  110
30  114
31  118
32  122
33  126
34  130
35  134
36  138
37  142
38  146

谢谢,

4 个答案:

答案 0 :(得分:0)

select sum(select top 4 Value from [table] order by Value Desc)

或者,或许

select sum(value)
from [Table]
where Value >= (Max(Value) - 4)

我实际上没有尝试过其中任何一种 - 现在也不能,但它们应该让你非常接近。

答案 1 :(得分:0)

假设ID可以提供最后4行。

SELECT SUM([SUM])
FROM
    (
    SELECT TOP 4 [SUM] FROM myTable ORDER BY ID DESC
    ) foo

每次查询时,它都会读取最后4行。

如果这是错误的(例如,你想要每个连续4行的总和),那么请给出样本输出

答案 2 :(得分:0)

快速尝试,它会获得您在问题中发布的结果(除了前3行不是NULL)。假设VALUE字段是唯一的并且按升序排列:

-- Create test TABLE with 38 values in
DECLARE @T TABLE (Value INTEGER)
DECLARE @Counter INTEGER
SET @Counter = 1
WHILE (@Counter <= 38)
    BEGIN
        INSERT @T VALUES(@Counter)
        SET @Counter = @Counter + 1
    END

-- This gives the results   
SELECT t1.VALUE, x.Val
FROM @T t1
    OUTER APPLY(SELECT SUM(VALUE) FROM (SELECT TOP 4 VALUE FROM @T t2 WHERE t2.VALUE <= t1.VALUE ORDER BY t2.VALUE DESC) x) AS x(Val)
ORDER BY VALUE

至少,你应该看到我前进的方向。

答案 3 :(得分:0)

如果您的Value列是连续的

,则可以使用以下内容
;WITH q (Value) AS (
    SELECT  1
    UNION ALL
    SELECT  q.Value + 1
    FROM    q
    WHERE   q.Value < 38
)

SELECT  q.Value
        , CASE WHEN q.Value >= 4 THEN q.Value * 4 - 6 ELSE NULL END
FROM    q       

否则你可能会使用这样的东西

;WITH q (Value) AS (
    SELECT  1
    UNION ALL
    SELECT  q.Value + 1
    FROM    q
    WHERE   q.Value < 38
)
, Sequential (ID, Value) AS (
    SELECT  ID = ROW_NUMBER() OVER (ORDER BY Value)
            , Value
    FROM    q
)
SELECT  s1.Value
        , [SUM] = s1.Value + s2.Value + s3.Value + s4.Value
FROM    Sequential s1
        LEFT OUTER JOIN Sequential s2 ON s2.ID = s1.ID - 1
        LEFT OUTER JOIN Sequential s3 ON s3.ID = s2.ID - 1
        LEFT OUTER JOIN Sequential s4 ON s4.ID = s3.ID - 1

请注意,示例中的表q是实际表的存根。然后实际的陈述变为

;WITH Sequential (ID, Value) AS (
    SELECT  ID = ROW_NUMBER() OVER (ORDER BY Value)
            , Value
    FROM    YourTable
)
SELECT  s1.Value
        , [SUM] = s1.Value + s2.Value + s3.Value + s4.Value
FROM    Sequential s1
        LEFT OUTER JOIN Sequential s2 ON s2.ID = s1.ID - 1
        LEFT OUTER JOIN Sequential s3 ON s3.ID = s2.ID - 1
        LEFT OUTER JOIN Sequential s4 ON s4.ID = s3.ID - 1