0

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

4

1 回答 1

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;
于 2013-01-28T17:29:08.977 回答