SQL display MIN()列,并显示其他列
我正在编写一份报告,其中需要显示学生id、分数和分数提交的最低日期/时间。该表将包含每个学生在多天内的多个分数 我遇到的问题(使用下面的示例代码)是,我会为每个分数获得一个新行,而不是每个学生只显示一行学生id、分数和日期 示例源表列 学生证| 得分| 记分日SQL display MIN()列,并显示其他列,sql,sql-server,Sql,Sql Server,我正在编写一份报告,其中需要显示学生id、分数和分数提交的最低日期/时间。该表将包含每个学生在多天内的多个分数 我遇到的问题(使用下面的示例代码)是,我会为每个分数获得一个新行,而不是每个学生只显示一行学生id、分数和日期 示例源表列 学生证| 得分| 记分日 select tests.student_id ,tests.score ,min(score_date) from tests group by tests.student_id ,tests.
select tests.student_id
,tests.score
,min(score_date)
from tests
group by tests.student_id
,tests.score
您可以使用行编号()
进行此操作
select * from (
select t1.student_id
,t1.score
,row_number() over (partition by t1.student_id order by t1.score_date) rn
,t1.score_date
from tests t1) t
where t.rn = 1
使用相关子查询
还有一个技巧
select student_id
, min(score_date) score_date
, (select top 1 score from tests where score_date = min(t.score_date) and student_id = t.student_id) as score
from tests t
group by student_id
或者,如果您正在使用sql server 2012及更高版本。您可以最大限度地使用first\u value()
函数
select distinct first_value(student_id) over (partition by student_id order by score_date)
, first_value(score_date) over (partition by student_id order by score_date)
, first_value(score) over (partition by student_id order by score_date)
from tests t
group by student_id
试试这个
SELECT student_id, score, score_date
FROM tests T
INNER JOIN (SELECT student_id, Min(score_date) AS score_date FROM tests) X
ON T.student_id = X.student_id AND T.score_date = X.score_date
如果你想知道每个学生得分最低时的所有日期 然后,我想到了窗口函数。按升序
得分排序
WITH CTE_STUDENT_SCORES AS
(
SELECT student_id, score, score_date
, DENSE_RANK() OVER (PARTITION BY student_id ORDER BY score ASC) AS StudentAscendingScoreRank
FROM tests
)
SELECT student_id, score, score_date
FROM CTE_STUDENT_SCORES
WHERE StudentAscendingScoreRank = 1
ORDER BY student_id, score_date
如果只需要学生最低分数的最新分数日?然后可以限制行数。
按升序得分和降序得分日期排序
WITH CTE_STUDENT_SCORES AS
(
SELECT student_id, score, score_date
, ROW_NUMBER() OVER (PARTITION BY student_id ORDER BY score ASC, score_date DESC) AS StudentAscendingScoreRownum
FROM tests
)
SELECT student_id, score, score_date
FROM CTE_STUDENT_SCORES
WHERE StudentAscendingScoreRownum = 1
ORDER BY score_date DESC, student_id;
使用
row\u number()
窗口函数获取最早日期您希望在学生ID/最低日期旁边看到的分数是多少?