分组表达式可以与变量赋值一起使用吗?

时间:2014-06-08 16:45:57

标签: mysql sql

我正在尝试计算分组结果集中的行差异(例如MySQL difference between two rows of a SELECT Statement):

create table test (i int not null auto_increment, a int, b int, primary key (i));
insert into test (a,b) value (1,1),(1,2),(2,4),(2,8);

给出

| a | b
---------
| 1 | 1
| 1 | 2
| 2 | 4
| 2 | 8

这是包含组和max(group)结果列的简单SQL:

select 
    data.a,
    max(data.b)
from
    (
        select a, b
        from test
        order by i
    ) as data
group by a
order by a

显而易见的结果是

| a | max(data.b)
-----------------
| 1 | 2
| 2 | 8

我失败的地方是我想要计算分组列上的逐行差异:

set @c:=0;
select 
    data.a,
    max(data.b),
    @c:=max(data.b)-@c
from
    (
        select a, b
        from test
        order by i
    ) as data
group by a
order by a

仍然给出:

| a | max(data.b) | @c:=max(data.b)-@c
--------------------------------------
| 1 | 2           | 2 (expected 2-0=2)
| 2 | 8           | 8 (expected 8-2=6)

有人可以突出显示为什么@c变量没有按预期从分组行更新到分组行吗?

2 个答案:

答案 0 :(得分:1)

SELECT data.a
     , data.b
     , @c := data.b - @c
FROM (
        SELECT a
             , max(b) AS b
        FROM test
        GROUP BY a
     ) AS data
ORDER BY a

Example

答案 1 :(得分:0)

'记录'解决方案可能看起来像这样......

SELECT x.* 
     , @c := b - @c c
  FROM test x 
  JOIN 
     ( SELECT a,MAX(b) max_b FROM test GROUP BY a ) y 
    ON y.a = x.a 
   AND y.max_b = x.b
  JOIN (SELECT @c:= 0) vals;