3

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

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

亲切的问候

4

1 回答 1

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;
于 2013-01-26T15:07:45.817 回答