我在一个学生数据库中有一个表,其中有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我必须选择id 1的所有记录,其中术语是'2012夏季‘、'2012秋季’、'2012春季‘,date1和date2是最近更新的记录。
发布于 2016-11-23 21:51:43
从描述来看,我认为最近更新的是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值的记录,将返回重复项。
https://stackoverflow.com/questions/40766263
复制相似问题