最大时间戳记录

时间:2021-06-04 13:40:23

标签: sql hiveql

我有 2 张桌子要加入。

我在 CTE 中使用,并在我加入之后使用。

我想为每个 student_id 从 Table2 中选择最新的记录(因此对于 Table1 中的每条记录,我将只有 table2 中的一条记录要加入)。连接是通过左连接到 table1。

我怎么能做到?我尝试了很多方法,都没有找到解决方案。

主表-表1 组队_id 班级 评论

表 2

老师_id 学号_id 老师的名字 Recored_timestamp

2 个答案:

答案 0 :(得分:0)

试试这个:

WITH cte1 AS (
    SELECT
        *
    FROM
        table1
), cte2_aux AS (
    SELECT
        t2.*,
        ROW_NUMBER() OVER(
            PARTITION BY student_id
            ORDER BY
                recored_timestamp DESC
        ) rn
    FROM
        table2
), cte2 AS (
    SELECT
        *
    FROM
        cte2_aux
    WHERE
        rn = 1
)
SELECT
    *
FROM
    cte2 c2
    LEFT JOIN c1 ON c1.student_id = c2.student_id;

答案 1 :(得分:0)

我附上了一张解释这个的照片

enter image description here

相关问题