当行对应于其他列中的 MAX 时保留 NULL
Keep NULL when Rows Corresponds to MAX in Other Column
我在 SQL 服务器中遇到 GROUP BY
/ MAX(.)
情况。请考虑以下 table、Tab1
,以及每年重复的课程条目:
学生姓名
课程
开始日期
完成日期
N1
C1
2020-01-01
空
N1
C1
2019-01-01
2019-02-01
N1
C1
2018-01-01
2018-02-01
N2
C1
2020-01-01
2020-02-01
N2
C1
2019-01-01
空
N2
C1
2018-01-01
2018-02-01
N2
C2
2020-01-01
空
N2
C2
2019-01-01
2019-02-01
N2
C2
2018-01-01
2018-02-01
A NULL
表示学生没有完成课程。我想访问每门课程中每个学生的最新尝试。
的输出
SELECT studentName, Course, MAX(startDate), MAX(finishDate)
FROM Tab1
GROUP BY studentName, Course
是:
学生姓名
课程
开始日期
完成日期
N1
C1
2020-01-01
2019-02-01
N2
C1
2020-01-01
2020-02-01
N2
C2
2020-01-01
2019-02-01
这不是正确的输出,因为 N1 <-> C1
和 N2 <-> C2
组合应该有 NULL
。如何在保留 NULL
的同时获取 MAX(finishDate)
?
谢谢。
假设您想要记录每个学生和课程组合的最晚开始日期 - 一种方法是使用 row_number 函数。
像这样:
;with student_select as (
SELECT
studentName
, Course
, startDate
,finishDate
,row_number() over (partition by studentName,Course order by startdate desc) as row_num
FROM Tab1
)
Select
studentName
, Course
, startDate
,finishDate
from student_select
where row_num = 1
请参阅此处的 SQL FIDDLE 示例:- http://www.sqlfiddle.com/#!18/9ad7f/3
通过 max(startdate) 按学生姓名和课程分组获取最后一个开始日期。然后自己再次加入table以获得相应的完成日期。
select a.studentName
, a.course
, a.last_start_date as start_date
, b.finishdate
from (
select studentName
, course
, max(startdate) last_start_date
from Tab1
group by studentName, course) a, Tab1 b
where a.studentName = b.studentName
and a.course = b.course
and a.last_start_date = b.startdate;
我在 SQL 服务器中遇到 GROUP BY
/ MAX(.)
情况。请考虑以下 table、Tab1
,以及每年重复的课程条目:
学生姓名 | 课程 | 开始日期 | 完成日期 |
---|---|---|---|
N1 | C1 | 2020-01-01 | 空 |
N1 | C1 | 2019-01-01 | 2019-02-01 |
N1 | C1 | 2018-01-01 | 2018-02-01 |
N2 | C1 | 2020-01-01 | 2020-02-01 |
N2 | C1 | 2019-01-01 | 空 |
N2 | C1 | 2018-01-01 | 2018-02-01 |
N2 | C2 | 2020-01-01 | 空 |
N2 | C2 | 2019-01-01 | 2019-02-01 |
N2 | C2 | 2018-01-01 | 2018-02-01 |
A NULL
表示学生没有完成课程。我想访问每门课程中每个学生的最新尝试。
SELECT studentName, Course, MAX(startDate), MAX(finishDate)
FROM Tab1
GROUP BY studentName, Course
是:
学生姓名 | 课程 | 开始日期 | 完成日期 |
---|---|---|---|
N1 | C1 | 2020-01-01 | 2019-02-01 |
N2 | C1 | 2020-01-01 | 2020-02-01 |
N2 | C2 | 2020-01-01 | 2019-02-01 |
这不是正确的输出,因为 N1 <-> C1
和 N2 <-> C2
组合应该有 NULL
。如何在保留 NULL
的同时获取 MAX(finishDate)
?
谢谢。
假设您想要记录每个学生和课程组合的最晚开始日期 - 一种方法是使用 row_number 函数。
像这样:
;with student_select as (
SELECT
studentName
, Course
, startDate
,finishDate
,row_number() over (partition by studentName,Course order by startdate desc) as row_num
FROM Tab1
)
Select
studentName
, Course
, startDate
,finishDate
from student_select
where row_num = 1
请参阅此处的 SQL FIDDLE 示例:- http://www.sqlfiddle.com/#!18/9ad7f/3
通过 max(startdate) 按学生姓名和课程分组获取最后一个开始日期。然后自己再次加入table以获得相应的完成日期。
select a.studentName
, a.course
, a.last_start_date as start_date
, b.finishdate
from (
select studentName
, course
, max(startdate) last_start_date
from Tab1
group by studentName, course) a, Tab1 b
where a.studentName = b.studentName
and a.course = b.course
and a.last_start_date = b.startdate;