我在学生数据库中有一个包含49列的表。每位学生都被分配了一个唯一的ID。日期还有其他两列。 date1具有将记录插入数据库的日期。还有另一列date2,其中显示了学生注册课程的日期。此外,学生的注册在学期期间被处理不止一次,因此有多个学生具有不同日期的实例。我想从表中删除重复项。
表格与此类似
id Date1 Date2 TERM_CODE TERM
1 2016-07-06 2011-11-01 201210 2012 Spring
2 2016-07-06 2011-11-17 201210 2012 Spring
4 2016-07-06 2011-11-17 201210 2012 Spring
3 2016-07-06 2011-11-17 201210 2012 Spring
1 2016-07-16 2011-11-09 201210 2012 Spring
2 2016-07-16 2011-11-17 201210 2012 Spring
1 2016-07-16 2011-11-01 201230 2012 Summer
1 2016-07-06 2011-11-13 201230 2012 Summer
1 2016-07-16 2011-11-03 201260 2012 Fall
1 2016-07-06 2011-11-17 201260 2012 Fall
我必须选择身份证1的所有记录,其中的条款是“2012年夏季”,“2012年秋季”,“2012年春季”和#39; 2012年春季' date1和date2是最近更新的。
答案 0 :(得分:1)
从描述中,我认为最近更新意味着date2
。如果是这样,一种方法使用窗口函数:
select t.*
from (select t.*,
row_number() over (partition by id order by date2 desc, date1 desc) as seqnum
from t
) t
where seqnum = 1;
即使学生有多行具有相同的id
,这也只能保证每date2
行一行。
更传统的SQL方法:
select t.*
from t
where t.date2 = (select max(t2.date2)
from t t2
where t2.id = t.id);
如果学生有多个具有相同date2
值的记录,将返回重复项。