How to select id with max date group by category in PostgreSQL?

前端 未结 4 1391
死守一世寂寞
死守一世寂寞 2020-11-27 10:54

For an example, I would like to select id with max date group by category, the result is: 7, 2, 6

id  category  date
1   a         2013-01-01
2   b         2         


        
相关标签:
4条回答
  • 2020-11-27 11:40

    Try this one:

    SELECT t1.* FROM Table1 t1
    JOIN 
    (
       SELECT category, MAX(date) AS MAXDATE
       FROM Table1
       GROUP BY category
    ) t2
    ON T1.category = t2.category
    AND t1.date = t2.MAXDATE
    

    See this SQLFiddle

    0 讨论(0)
  • 2020-11-27 11:42

    This is a perfect use-case for DISTINCT ON (Postgres specific extension of standard DISTINCT):

    SELECT DISTINCT ON (category)
           id  -- , category, date -- add any other column (expression) from the same row
    FROM   tbl
    ORDER  BY category, "date" DESC;
    

    Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

    • PostgreSQL sort by datetime asc, null first?

    DISTINCT ON is simplest and fast. Detailed explanation in this related answer:

    • Select first row in each GROUP BY group?

    For big tables consider this alternative approach:

    • Optimize groupwise maximum query

    Performance optimization for many rows per category:

    • Optimize GROUP BY query to retrieve latest record per user
    0 讨论(0)
  • 2020-11-27 11:52

    Another approach is to use the first_value window function: http://sqlfiddle.com/#!12/7a145/14

    SELECT DISTINCT
      first_value("id") OVER (PARTITION BY "category" ORDER BY "date" DESC) 
    FROM Table1
    ORDER BY 1;
    

    ... though I suspect hims056's suggestion will typically perform better where appropriate indexes are present.

    A third solution is:

    SELECT
      id
    FROM (
      SELECT
        id,
        row_number() OVER (PARTITION BY "category" ORDER BY "date" DESC) AS rownum
      FROM Table1
    ) x
    WHERE rownum = 1;
    
    0 讨论(0)
  • 2020-11-27 11:57

    SELECT id FROM tbl GROUP BY cat HAVING MAX(date)

    0 讨论(0)
提交回复
热议问题