使用 group by 的 MySql 变量顺序计算无法正常工作

标签 mysql select group-by

如下表和查询给出所需结果。

SELECT col1, col2, col3, @a:=@a+(col2+col3) col4
FROM test
JOIN (SELECT @a:=0)t

col1 | col2 | col3 | col4
-------------------------
a    |  1   |  1   |  2
b    |  2   |  0   |  4
c    |  3   |  0   |  7
a    |  0   |  2   |  9

但是当我使用 group by 时它不能正常工作。你有什么好的解决办法吗?

SELECT col1, SUM(col2)col2, SUM(col3)col3, @a:=@a+SUM(col2+col3) col4
FROM test
JOIN (SELECT @a:= 0)t
GROUP BY col1

    col1 | col2 | col3 | col4
    -------------------------
    a    |  1   |  3   |  4
    b    |  2   |  0   |  2  << It will be 6
    c    |  3   |  0   |  3  << It will be 9

第一行已正确获取。但是 row2 和 row3 没有像前面的例子那样计算前一行的 col4 值。我不明白问题出在哪里!

最佳答案

试试这个代码,它对我有用:)

SELECT col1, col2,col3, @a:=@a+(col2+col3) col4
FROM (select col1,sum(col2)col2,sum(col3)col3 from test group by col1) as tes
JOIN (SELECT @a:= 0)t

我为你做了一个 fiddle :

http://sqlfiddle.com/#!2/9b3ac/44

希望对您有所帮助;)

关于使用 group by 的 MySql 变量顺序计算无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318806/

相关文章:

android - Android 应用程序中的 SQL 数据库多久更新一次

php - 如何根据查询中字段的相对位置对表中的列进行排序?

php - Dreamweaver PHP 登录注销有多安全?

android - 无法在 Android/Gingerbread 上使用 Flexslider/SwipeJS 激活选择

php - 尝试将托管 Web 应用程序连接到本地数据库?

jquery - 多个选择会禁用彼此的选项

javascript - 如何使用 typescript 对象数组而不是单一类型的元素(例如字符串)来实现 ngx-select-dropdown

mysql - 从许多行中选择值或基于列的另一个值

python - 如何生成预解压列表?

php - 按一列对二维数据进行分组并对另一列求和以生成关联数组