在MYSQL中的表中选择同一行中三个连续值的总和

时间:2016-10-07 13:59:33

标签: mysql sql

请参阅表格以提供sql查询以获得类似的结果。

ggplot(df2, aes(x = DateYM, y=Qty))

期望的输出:

id value
1  10
2  15
3  30
4  10
5  11
6  12

http://sqlfiddle.com/#!9/21cbc8

1 个答案:

答案 0 :(得分:1)

将ID除以3,将其四舍五入,将其分组(使用sum):

SELECT 
    ceiling(id / 3) AS NewID, 
    sum(Value)      AS SumValue
FROM MyTable
GROUP BY ceiling(id / 3)

使用变量:

SET @GroupVar = 3;  -- Set this number to whatever you want to group by

SELECT 
    ceiling(id / @GroupVar) AS NewID, 
    sum(Value)      AS SumValue
FROM MyTable
GROUP BY ceiling(id / @GroupVar);