比较使用CASE和USER VARIABLES

时间:2013-01-26 14:49:53

标签: mysql

我有这张桌子,我只想看看AB

ID     CODE       COUNT   
102    AB         9
101    AB         8
100    AC         23    //not important!!!!
99     AB         7
98     AB         6
97     AB         5
96     AB         0

转到这个

ID    NEWID     CODE       COUNT   
102   102       AB         9
101   101       AB         8
99    100       AB         7
98    99        AB         6
97    98        AB         5
96    97        AB         0

使用

SELECT
t.ID, t.CODE, t.COUNT,
@PREVCOUNT - t.COUNT DIFFERENCE,
@PREVCOUNT := t.COUNT  -- Updates for the next iteration, so it
                       -- must come last! 
FROM
(SELECT ID, CODE, COUNT FROM some_table WHERE CODE = 'AB' ORDER BY ID DESC) t,
(SELECT @PREVCOUNT := NULL) _uv;

http://sqlfiddle.com/#!2/e0b8b/36/0

所以

Step 1: 9 - 1 = 1
Step 2: 8 - 7 = 1
Step 3: 7 - 6 = 1
Step 4: 6 - 5 = 1
Step 5: 5 - 0 = 5

现在可能有我

的情况
ID    NEWID     CODE       COUNT   
102   102       AB         4
101   101       AB         2
99    100       AB         1
98    99        AB         0
97    98        AB         7
96    97        AB         0

然后我想算一下

Step 1: 4 - 2 = 2
Step 2: 2 - 1 = 1
Step 3: 1 - 0 = 1
Step 4: 0 - 7 = -7      //want  to discard this negative value
Step 5: 5 - 0 = 7

我想放弃第4步,因为这是否定的。

现在我使用此代码来丢弃负值

SELECT
t.ID, t.CODE, t.COUNT,
@PREVCOUNT,
@PREVCOUNT - t.COUNT DIFFERENCE,
CASE @PREVCOUNT - t.COUNT WHEN @PREVCOUNT - t.COUNT >= 0 THEN 'equal or bigger' ELSE 'smaller' END,
@PREVCOUNT := t.COUNT  -- Updates for the next iteration, so it
                       -- must come last!
FROM
(SELECT ID, CODE, COUNT FROM some_table WHERE CODE = 'AB' ORDER BY ID DESC) t,
(SELECT @PREVCOUNT := NULL) _uv;

执行此代码后,我希望看到比较的大小等于或大于0,而不是非常不同的结果。

在链接下方查看我的意思:

http://sqlfiddle.com/#!2/6be4a/1

我真的很想知道这里出了什么问题,我很乐意找到解决方案。

亲切的问候

1 个答案:

答案 0 :(得分:1)

这个怎么样:

http://sqlfiddle.com/#!2/6be4a/7

select * from (
SELECT
    t.ID, t.CODE, t.COUNT,
    @PREVCOUNT,
    @PREVCOUNT - t.COUNT DIFFERENCE,
    CASE @PREVCOUNT - t.COUNT WHEN @PREVCOUNT - t.COUNT >= 0 THEN 'equal or bigger' ELSE 'smaller' END,
    @PREVCOUNT := t.COUNT  -- Updates for the next iteration, so it
                           -- must come last!
FROM
    (SELECT ID, CODE, COUNT FROM some_table WHERE CODE = 'AB' ORDER BY ID DESC) t,
    (SELECT @PREVCOUNT := NULL) _uv
group by t.id, t.code
)x
where x.difference >= 0;