【问题标题】:Get the max month from a query that returns several years从返回几年的查询中获取最大月份
【发布时间】:2021-02-09 03:10:15
【问题描述】:

我有一张带日期的表格,每个月有一个日期(有些月份会丢失,但这是意料之中的),但会返回几年。我只需要得到最近一个月。因此,如果我有 2020 年第 8、7、6 个月等月份的数据,则返回这些 startDate。在第 10 个月、第 11 个月和第 12 个月,它应该返回 2019 年的 StartDate 或它找到的最新日期。 id 和 courseLength 是表的一部分,但与此任务无关。 StartDate 是日期类型。

这是表格的前 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

【问题讨论】:

  • id 跟这个问题有关系吗? courseLength 吗? StartDate的数据类型是什么?请阅读this 了解一些改进问题的技巧。

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


【解决方案1】:

你可以使用窗口函数:

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

【讨论】:

    【解决方案2】:

    或者你可以使用这个:

    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
    

    【讨论】:

      【解决方案3】:

      试试这个

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多