选择具有最长日期

时间:2017-07-27 08:16:23

标签: sql postgresql

示例数据。

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

我想得到像这样的输出 -

Date           Subject
20170616       Maths
20170616       hindi

3 个答案:

答案 0 :(得分:0)

尝试此查询:

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

答案 1 :(得分:0)

查看window functionscte

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

答案 2 :(得分:0)

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

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

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