1

我有这张表,我只想看 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, @NEWID := COALESCE(@NEWID - 1, t.ID) AS NEWID, t.CODE, t.COUNT
FROM
(SELECT ID, CODE, COUNT FROM some_table WHERE CODE = 'AB' ORDER BY ID DESC) t,
(SELECT @NEWID := NULL) _uv;

http://sqlfiddle.com/#!2/e0b8b/1/0

现在我想计算每个连续 NEWID 的差异。

所以

Step 1: 9 - 8 = 1
Step 2: 8 - 7 = 1
Step 3: 7 - 6 = 1
Step 4: 6 - 5 = 1
Step 5: 5 - 0 = 5

我习惯这样做

LEFT OUTER JOIN some_table t2 ON t.ID = ( t2.ID + 1 ) 

然后取t2.count和t.count之间的差,但是现在当我使用COALESCE时,我无法选择这个NEWID,所以下面的代码不起作用。

LEFT OUTER JOIN some_table t2 ON t.NEWID = ( t2.NEWID + 1 ) 

那么我应该如何解决这个问题呢?

4

2 回答 2

1

尝试这个:

SELECT 
 t1.ID as ID1, 
 t2.ID as ID2, 
 t1.CODE as CODE, 
 t1.COUNT as C1, 
 t2.COUNT as C2,
 t2.COUNT - t1.COUNT as DIFF
FROM 
  some_table t1 
  INNER JOIN some_table t2 ON t1.ID < t2.ID AND t1.CODE = t2.CODE
WHERE
  t1.CODE='AB'
  AND NOT EXISTS 
   (SELECT * FROM some_table t3
    INNER JOIN some_table t4 ON t3.ID < t4.ID and t3.CODE = t4.CODE
    WHERE 
        t3.CODE='AB'
        AND t1.ID = t3.ID
        AND t4.ID < t2.ID 
      )
ORDER BY t1.ID

另一种方法是使用 LIMIT:

SELECT
 t.ID1 AS ID,
 t.CODE as CODE,
 t.C2-t.C1 AS DIFF
FROM
(
SELECT 
 t1.ID as ID1, 
 t1.CODE as CODE, 
 t1.COUNT as C1, 
 (SELECT t.COUNT 
  FROM some_table t
  WHERE t.ID > t1.ID AND t.CODE=t1.CODE 
  ORDER BY t.ID 
  LIMIT 1) as C2
FROM 
  some_table t1 
WHERE
  t1.CODE='AB'
ORDER BY t1.ID) t
ORDER BY t.ID1

http://sqlfiddle.com/#!2/e0b8b/24

于 2013-01-26T11:42:54.813 回答
1

哦,就是你需要顺序 ID 的原因。好吧,您也可以为此使用用户变量,甚至不需要NEWID!由于您正在做这样的事情,因此您最好阅读一下用户变量的工作原理

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;

SQL小提琴

于 2013-01-26T12:09:25.350 回答