如何使用 SQL 组过滤具有最小日期值的行?

How to use SQL group to filter rows with minimum date value?

我有以下 table:

STUDENT_CODE REGION_CODE COURSE_CODE SUBMIT_DATE
46588225 N AAA00004 2017-03-16 06:08:40.031000
85788225 N AAA00004 2017-03-24 12:14:29.493000
85789271 N AAA00004 2017-06-24 12:14:29.493000
884444 N B0006 2017-10-05 00:33:08.627000
2558855 N B0006 2019-08-02 02:47:22.996000

我想达到这样的结果,即只选择具有 region_code 和 course_code 的最小值 submit_date 的学生代码。即

STUDENT_CODE REGION_CODE COURSE_CODE SUBMIT_DATE
46588225 N AAA00004 2017-03-16 06:08:40.031000
884444 N B0006 2017-10-05 00:33:08.627000

如何使用 group by 和 FETCH FIRST 1 ROW ONLY 实现此目的?我做了如下操作,但没有用。

select a.STUDENT_CODE,a.REGION_CODE,a.COURSE_CODE,min(a.SUBMIT_DATE) from STUDENT as a where a.REGION_CODE='N' and a.COURSE_CODE IN ('AAA00004','B0006') group by a.STUDENT_CODE, a.REGION_CODE, a.COURSE_CODE order by a.COURSE_CODE asc FETCH FIRST 1 ROW ONLY;

您可以使用相关子查询

select a.STUDENT_CODE,a.REGION_CODE,a.COURSE_CODE,SUBMIT_DATE
from STUDENT as a 
where a.REGION_CODE='N' and a.COURSE_CODE IN ('AAA00004','B0006')
and SUBMIT_DATE in
   (select min(SUBMIT_DATE) from STUDENT as b where a.COURSE_CODE=b.COURSE_CODE)

我建议为此使用 row_number()

select s.*
from (select s.*,
             row_number() over (partition by region_code, course_code order by submit_date desc) as seqnum
      from student s
      where s.REGION_CODE = 'N' and
            s.COURSE_CODE IN ('AAA00004', 'B0006')
     ) s
where seqnum = 1;