我的表结构如下面的desc命令
sr group name status
4 class11 ghanshyam Joined
3 class11 ghanshyam Removed
2 class11 ghanshyam suspended
1 class11 ghanshyam joined
现在我想获取状态为Removed的组class11中的所有记录。
所以我的查询将是
select * from table where group = 'class11' and status='Removed' group by name
但现在ghanshyam在状态被删除后重新加入了组,我们正在复制条目,因此它不应计入已删除状态,对于已暂停的帐户也是如此。
那么如何从表中获取所需的行
答案 0 :(得分:0)
您应该在所有情况下检索记录,如下所示:
select * from table where group = 'class11'
执行此操作后,您可以检查最后一个状态,如果已删除或加入。
答案 1 :(得分:0)
SELECT t1.* from [table] t1
INNER JOIN
( SELECT MAX(sr) AS nsr ,[group] ,[name] FROM [table] GROUP BY [group] ,[name] ) t2
ON t2.nsr = t1.sr
AND t1.status='Removed'
答案 2 :(得分:0)
试试这个:
SELECT * FROM yourTable
WHERE group = 'class11' AND status ='Removed'
AND (SELECT MAX(sr) FROM yourTable WHERE group = 'class11' AND status ='Joined') < sr
GROUP BY name
希望这会对你有所帮助:) 如有任何澄清,请添加评论。
答案 3 :(得分:0)
尝试此查询,它将获得removed
SELECT * FROM tbl_name t WHERE t.sr IN
(SELECT max(t1.sr) FROM tbl_name t1 WHERE `group` = 'class11' GROUP BY t1.`name`)
AND t.status = 'Removed'
检查这样小提琴: http://sqlfiddle.com/#!9/ef189a/1