gpt4 book ai didi

mysql - 比较使用 CASE 和 USER VARIABLES

转载 作者:可可西里 更新时间:2023-11-01 08:50:52 26 4
gpt4 key购买 nike

我有这张表,我只想看 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

我真的很想知道这里出了什么问题,我很想有一个解决方案。

亲切的问候

最佳答案

这个怎么样:

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;

关于mysql - 比较使用 CASE 和 USER VARIABLES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com