我有这张桌子,我只想看看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
然后我想计算具有CODE'AB'
的特定ID之间的差异所以
Step 1: 9 - 8 = 1 // (corrected sample data. this line was wrong)
Step 2: 8 - 7 = 1
Step 3: 7 - 6 = 1
Step 4: 6 - 5 = 1
Step 5: 5 - 0 = 5
我这是由@bonCodigo提出的这个查询
select ID, DIFFERENCE,
COUNT from (
SELECT
t.ID, t.CODE, t.COUNT,
@PREVCOUNT,
@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
group by t.id, t.code
)x
where x.difference >= 0
order by ID DESC;
由于我的新传入数据有时会重置计数,因此它从0开始计数直到无处可寻。
所以有时我会按顺序获取数据:
ID COUNT
1. 0
2. 1
3. 2
4. 7
5. 4 // which means the counter has reset to 0 and counted up to 4 again.
6. 5
现在我的查询正在做什么,它只计算正面的变化并将其视为差异。
它的作用是什么:
Step 1: 1 - 0 = 1
Step 2: 2 - 1 = 1
Step 3: 7 - 2 = 5
Step 4: 4 - 7 = -3 //discarded as this difference is smaller than 0
Step 5: 5 - 4 = 1
所以,如果我使用SUM(),我会得到 8 http://sqlfiddle.com/#!2/6924a/2
虽然我希望这个代码在出现负差异时从0开始计算
所以我想要的是:
Step 1: 1 - 0 = 1
Step 2: 2 - 1 = 1
Step 3: 7 - 2 = 5
Step 4: 4 - 7 = -3 BUT MAKE IT 4 because the counter started from 0 again.
Step 5: 5 - 4 = 1
所以,如果我使用SUM(),我会得到 12
答案 0 :(得分:1)
IF 语句可以解决问题。
IF((@PREVCOUNT - t.COUNT) < 0, @PREVCOUNT, (@PREVCOUNT - t.COUNT)) DIFFERENCE
这是工作小提琴:http://sqlfiddle.com/#!2/6924a/7/0
修改后的查询是:
select ID, DIFFERENCE,
COUNT from (
SELECT
t.ID, t.CODE, t.COUNT,
@PREVCOUNT,
IF((@PREVCOUNT - t.COUNT) < 0, @PREVCOUNT, (@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
group by t.id, t.code
)x
where x.difference >= 0
order by ID DESC;