从 returns 几年的查询中获取最大月份

Get the max month from a query that returns several years

我有一个 table 日期,每个月一个日期(有些月份会丢失,但这是预期的)但几年是 return。我只需要获取最新的月份。因此,如果我有 2020 年第 8、7、6 个月等的数据,那么 return 那些开始日期。对于第 10、11 和 12 个月,它应该 return 2019 年的 StartDate 或它找到的任何最新日期。 id 和 courseLength 是 table 的一部分,但与此任务无关。 StartDate 是日期类型。

这是 table

的前 15 行
id  StartDate   courseLength
153 2020-08-31  63
153 2020-07-31  35
153 2020-06-30  60
153 2020-05-31  17
153 2020-03-31  51
153 2020-01-31  59
153 2019-12-31  30
153 2019-10-31  51
153 2019-08-31  59
153 2019-06-30  54
153 2019-05-31  17
153 2019-03-31  56
153 2019-01-31  55
153 2018-12-31  27
153 2018-10-31  54

这就是我所期待的

id  StartDate   courseLength
153 2020-08-31  63
153 2020-07-31  35
153 2020-06-30  60
153 2020-05-31  17
153 2020-03-31  51
153 2020-01-31  59
153 2019-12-31  30
153 2019-10-31  51
153 2018-11-30  65
153 2018-09-31  53
153 2019-05-31  17
153 2018-04-30  13

您可以使用 window 函数:

select *
from (
    select t.*,
        row_number() over(partition by id, month(startdate) order by startdate desc) rn
    from mytable t
) t
where rn = 1

或者你可以使用这个:

select * from table
 join in (
        select 
          max(date) maxdate
          , id 
        from table
        group by 
          month(date) , id 
    ) max
  on max.id = table.id
  and max.maxdate = table.date

试试这个

SELECT
    R.id, R.StartDate, R.courseLength
FROM (
    SELECT
        id, StartDate, courseLength, RANK() OVER(PARTITION BY MONTH(StartDate) ORDER BY StartDate DESC) as rank
    FROM
        #t
    ) R
WHERE
    R.rank = 1