通过加入2个表来获取个人的最新记录

时间:2019-06-24 11:00:59

标签: sql greatest-n-per-group

我必须获取通过加入2个表得出的学生的最新记录:

table 1:      table 2:

id name       id  marks    EXAM attended time        status
--------      ----------------------------------------------
1  ABC         1   90     2019-04-05 06:00:00          PASS 
2  DEF         1   25     2018-06-05 08:00:00          FAIL 
               2   45     2019-03-05 06:00:00          FAIL
               2   22     2019-01-05 09:00:00          FAIL

在连接两个表时,我得到了:

#  name    marks   EXAM ATTENDED TIME         status 
------------------------------------------------------
1   ABC     90     2019-04-05 06:00:00          PASS    
2   ABC     25     2018-06-05 08:00:00          FAIL 
3   DEF     45     2019-03-05 06:00:00          FAIL   
4   DEF     22     2019-01-05 09:00:00          FAIL
5   DEF     55     2019-04-05 09:00:00          PASS
6   DEF     66     2019-05-05 09:00:00          PASS
7   DEF     99     2018-05-05 09:00:00          PASS

我想获取有关日期时间和名称的最新结果。

我需要的输出是:

id  name    marks   EXAM ATTENDED TIME         status
------------------------------------------------------
1   ABC     90     2019-04-05 06:00:00          PASS 
6   DEF     66     2019-05-05 09:00:00          PASS

4 个答案:

答案 0 :(得分:1)

您可以在下面使用相关子查询尝试

select * from table1 a1
inner join table2 a on a1.id=a.id
where  exam_attended_time in (select max(exam_attended_time) from table2 b where a.id=b.id)

或者您可以使用row_number()(如果您的数据库支持它)-

select * from 
(
select a.name,a1.*,row_number(partition by a.id order by exam_attended_time desc)rn from table1 a1
    inner join table2 a on a1.id=a.id
)X where rn=1

答案 1 :(得分:1)

您可以使用窗口函数(ROW_NUMBER)。

SELECT 
        x.id
    ,   x.NAME
    ,   x.marks
    ,   x.ExamAttendTime
    ,   x.status 
FROM 
    (
    SELECT 
            t1.id
        ,   t1.NAME
        ,   t2.marks
        ,   t2.ExamAttendTime
        ,   t2.status
        ,   ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY t2.ExamAttendTime DESC) AS ROWNUMBER
    FROM 
    dbo.Table1 t1 
    JOIN dbo.Table2 t2 ON t2.id = t1.id
    ) x
WHERE
    x.ROWNUMBER = 1

答案 2 :(得分:0)

我不知道您如何获取标记“ 99”和“ 66”以及EXAM参加时间的记录 '2019-05-05 09:00:00',该数据在表格本身中不可用。

尽管这可能会帮助您获取正确的数据。

select a.id,a.name,b.marks,b.[EXAM attended time],b.[status] from table 1 a 
join table 2 b on a.id=b.id where [EXAM attended time] in 
(select max([EXAM attended time])[EXAM attended time]from exam group by id)

答案 3 :(得分:0)

如果您使用的是SQL SERVER,则可以使用以下的TOP来获取最新记录

SELECT A.id, 
    A.name, 
    B.marks, 
    B.EXAM_attended_time, 
    B.Status
FROM table1 A
OUTER APPLY (SELECT TOP 1 *
            FROM table2 B WHERE B.id = A.id
            ORDER BY B.EXAM_attended_time DESC) B 
WHERE B.ID = A.id