计算最后一行,直到列值等于myql中的给定值

时间:2018-03-03 00:44:16

标签: mysql database

假设我的表只有两列;其中一个是AUTO_INCREMENT,另一个是包含在线数据......

A
B
C
A
A

我希望计算最后一行,直到找到给定值。

假设为,

A : 0 (Count From last to reach A)
C : 2 (Count From last to reach C)
B : 3 (Count From last to reach B)

1 个答案:

答案 0 :(得分:2)

获取每个项目的最高ID,然后计算具有更高ID的行数。

SELECT x.item, IFNULL(COUNT(y.id), 0) as count
FROM (SELECT item, MAX(id) AS lastid
      FROM yourTable
      GROUP BY item) AS x
LEFT JOIN yourTable AS y ON y.id > x.lastid
GROUP BY x.item

DEMO