【问题标题】:Select all the records having maximum date选择所有具有最大日期的记录
【发布时间】:2017-07-27 08:16:22
【问题描述】:

样本数据。

Date(YYYYMMDD)  Subject
20170602         Maths
20170602         Eng
20170609         Science
20170609         Hindi
20170616         Maths
20170616         hindi

我想得到这样的输出-

Date           Subject
20170616       Maths
20170616       hindi

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    试试这个查询:

    select
      t.subject,
      t.date
    from
    (
      select
        t.subject,
        t.date,
        max(t.date) over() AS max_date
      from
        {your_table} t
    ) t
    where
      t.date = t.max_date
    

    【讨论】:

      【解决方案2】:

      看看window functionscte

      WITH ranked AS (
          SELECT
              *,
              rank() OVER (ORDER BY "Date" DESC) AS r
          FROM _table_
      )
      SELECT 
          "Date", 
          "Subject"
      FROM ranked
      WHERE r = 1
      

      【讨论】:

        【解决方案3】:

        找到最大日期值并使用它过滤您的数据:

        select *
        from your_table
        where date = (select max(date) from your_table);
        

        如果您在date 列上有索引,那将非常有效。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-04-20
          • 1970-01-01
          • 1970-01-01
          • 2022-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多