0

我有这张表,我只想看 AB

ID     CODE       COUNT   
102    AB         7
101    AB         6
100    AC         23    //not important!!!!
99     AB         26
98     AB         1
97     AB         0
96     AB         50

我想计算每个步骤之间的差异,但中间有一些情况

情况1:如果值突然变成50,没有之前的值,取0作为之前的值。

情况2:如果差值突然为负,也取0作为之前的值。

所以我的结果应该是:

ID      COUNT   DIFFERENCE  
96      50      50      //CASE 1, take 0 as previous value
97       0       1
98       1      25
99      26       6      //CASE 2, take 0 instead of 26 as previous value
101      6       1

我现在拥有的代码是:

http://sqlfiddle.com/#!2/98051/3

我应该如何调整它以使其按我想要的方式工作?

亲切的问候

ps:如果您不清楚,请询问,我会尽力改善我的问题

4

2 回答 2

0

我不完全理解你想要完成什么,但我猜你想要这样的东西:

SET @previous_count:=0;

SELECT id, code, `count`, 
IF(`count` - @previous_count, `count`) as difference,
@previous_count:=`count` 
FROM table
于 2013-02-03T15:32:08.183 回答
0

我不知道在这种情况下“突然”是什么意思,但也许这样的事情对你有用......

SELECT a.id
     , a.code
     , a.count
     , b.count bcount
     , CASE WHEN a.count = 50 AND b.count IS NULL THEN 50
            WHEN a.count - b.count <= 0 THEN 0
            ELSE a.count - b.count
            END difference
  FROM 
     ( SELECT x.* 
            , COUNT(*) rank
         FROM some_table x
         JOIN some_table y
           ON y.code = x.code
          AND y.id <= x.id
        GROUP
           BY x.id
     ) a
  LEFT
  JOIN   
     ( SELECT x.* 
            , COUNT(*) rank
         FROM some_table x
         JOIN some_table y
           ON y.code = x.code
          AND y.id <= x.id
        GROUP
           BY x.id
     ) b
    ON b.code = a.code
   AND b.rank = a.rank -1;
于 2013-02-03T15:57:06.320 回答