【问题标题】:How do I return only the most recent record on a date field split into two如何仅返回日期字段上的最新记录,分为两部分
【发布时间】:2020-11-19 12:08:36
【问题描述】:

情景:A 人在两年内参加了 3 次 B 考试。该人将有三个条目。但是,我需要编写一个查询来告诉我参加过考试的人数(只有一个,最新的考试)。问题在于我有一个标记为 Test_Month (xx) 和 Test_year(xx) 的列。

我需要什么:我需要能够使用最近的测试月份和年份进行测试,基本上是他们最近参加的测试。 (例如(见下图)我需要,只有2/20的记录。)

我不知道如何根据单独的列 test_Month 和 test_year 在他们参加的最后一次测试中仅检索每人一条记录。

【问题讨论】:

    标签: sql database tsql datetime greatest-n-per-group


    【解决方案1】:

    你可以使用窗口函数:

    select *
    from (
        select 
            t.*, 
            row_number() over(
                partition last_name, firt_name 
                order by test_year desc, test_month desc
            ) rn
        from mytable t
    ) t
    where rn = 1
    

    【讨论】:

    • 那行得通,但只适用于这一年,我想知道我如何才能连续两年做到这一点,所以,如果他们参加了 3 次考试,2019 年两次,2020 年一次,我需要 2020 年记录。但是我从这个查询中学到了很多东西,非常感谢您
    猜你喜欢
    • 2010-11-22
    • 2018-03-18
    • 2011-09-12
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多