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

前端 未结 4 1409
死守一世寂寞
死守一世寂寞 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: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;
    

提交回复
热议问题