好吧,我在MySQL上有这些专栏:
id
id_conv
associated_statut
associated_statut 是1
和7
之间的数字。
我想要做的是,如果此id_conv
的最后 associated_statut为id_conv
,则仅计算2
。
示例:
-----------------------------------------------
| id | id_conv | associated_statut |
-----------------------------------------------
| 1 | 15 | 1 |
| 2 | 15 | 2 |
| 3 | 15 | 2 |
| 4 | 15 | 4 |
| 5 | 15 | 2 |
| 6 | 15 | 3 |
如果我想要id_conv
= 2,则不会计算associated_statut
,因为此id_conv
的最后一个associated_statut是3
。
我已经尝试过此查询:
SELECT COUNT(DISTINCT id_conv) FROM MyTable WHERE associated_statut = 2
但这并不能归还我想要的东西。
有没有办法在SQL中执行此操作?
感谢。
答案 0 :(得分:0)
SELECT COUNT(sub1.id_conv) FROM MyTable
INNER JOIN
(
SELECT DISTINCT id, FIRST(associated_statut ORDER BY id DESC)
group by id_conv
recent FROM MyTable
) sub1 ON sub1.id = MyTable.id
WHERE sub1.recent_associated_statut = 2
答案 1 :(得分:0)
也许,这对你有用:
SELECT count(t1.id) FROM mytable t1
INNER JOIN (SELECT id_conv, MAX(id) id FROM foo GROUP BY id_conv) t2
ON t1.id = t2.id
WHERE t1.associated_statut = 2
答案 2 :(得分:0)
我们可以在没有子查询的情况下做同样的事情。拥有更多数据需要更少的时间。
SELECT count(t1.id) FROM
mytable t1
LEFT JOIN
mytable t2
ON t1.id_conv = t2.id_conv
AND t1.id < t2.id
WHERE t2.id IS NULL
AND t1.associated_statut = 2;