我有一个包含以下列的表格; id,post_id,status和datetime。每次更新帖子(post_id)时,都会插入一行,其中包含最新的状态和日期时间戳。我创建了一个状态饼图。因此,我必须首先选择一个帖子的最新条目(忽略所有过去的更新),然后COUNT返回多少行并按状态分组。我的查询是什么样的?
答案 0 :(得分:1)
SELECT status, COUNT(*) AS statusCnt
FROM inspections
WHERE id IN (SELECT MAX(id) FROM inspections GROUP BY post_id)
GROUP BY status
未经考验的替代方案:
SELECT i1.status, COUNT(i1.*) AS statusCnt
FROM inspections i1
JOIN (
SELECT MAX(i2.id) AS maxID FROM inspections i2 GROUP BY i2.post_id
) AS innerTbl ON i1.id = innerTbl.id
GROUP BY i1.status
答案 1 :(得分:0)
SELECT count(*) FROM (SELECT *,MAX(time) FROM table GROUP BY post_id) As b
根据我对您的问题的解释,查询应该是这样的