我有一张表可以跟踪学生的不同资格。资格定期更新,因此许多学生拥有相同资格的多个记录。
我试图仅返回每个学生的每个资格的最新记录,没有重复。
到目前为止,我有这个,但我仍然坚持要删除重复的type_scrn
并返回最新的记录。
SELECT scrn.*
FROM cert_scrn scrn
WHERE scrn.id_scrn = (SELECT scrn2.id_scrn
FROM cert_scrn scrn2
WHERE scrn.id_scrn = scrn2.id_scrn
AND ( scrn2.type_scrn = 1
OR scrn2.type_scrn = 11
OR scrn2.type_scrn = 12
OR scrn2.type_scrn = 13 )
ORDER BY scrn2.expiredate_scrn DESC LIMIT 1)
ORDER BY scrn.idstu_scrn
返回:
id_scrn | idstu_scrn | type_scrn | expiredate_scrn
-------------------------------------------------
15 | 58 | 1 | 2010-01-26
1539 | 58 | 1 | 2015-06-21
5790 | 58 | 11 | 2016-02-20
5791 | 58 | 12 | 2016-02-20
5792 | 58 | 13 | 2016-02-20
我需要回复:
id_scrn | idstu_scrn | type_scrn | expiredate_scrn
---------------------------------------------------
1539 | 58 | 1 | 2015-06-21
5790 | 58 | 11 | 2016-02-20
5791 | 58 | 12 | 2016-02-20
5792 | 58 | 13 | 2016-02-20
答案 0 :(得分:1)
您需要加入子查询,查找每个idstu_scn
,type_scrn
组的最长日期。
因此,获取max(date)
的查询将是:
select idstu_scrn, type_scrn, max(expiredate_scrn) mdate
from cert_scrn
group by idstu_scrn, type_scrn
然后我们再次需要再次加入cert_scrn
表,找到其余的详细信息。
select scrn.*
from cert_scrn scrn
inner join (
select idstu_scrn, type_scrn, max(expiredate_scrn) mdate
from cert_scrn
group by idstu_scrn, type_scrn ) q
on scrn.idstu_scrn = q.idstu_scrn and scrn.type_scrn = q.type_scrn and scrn.expiredate_scrn = q.mdate
where scrn.type_scrn = 1
or scrn.type_scrn = 11
or scrn.type_scrn = 12
or scrn.type_scrn = 13
答案 1 :(得分:0)
请根据主键检查这个,在这种情况下似乎正常工作:
SELECT * FROM cert_scrn WHERE id_scrn IN
(SELECT MAX(id_scrn) FROM cert_scrn GROUP BY idstu_scrn, type_scrn);