PostgreSQL - “DISTINCT ON” and “GROUP BY” syntax

前端 未结 2 763
悲&欢浪女
悲&欢浪女 2021-02-05 12:07

I realized that a database query was returning unexpected results do to my improper use of \"DISTINCT ON\" and \"GROUP BY\"

I\'m hoping someone can set me straight on th

2条回答
  •  别那么骄傲
    2021-02-05 12:35

    It is probably not the best way of dealing with this but you can try using window function:

    SELECT DISTINCT object_id, MAX(event_timestamp)
    OVER (PARTITION BY object_id)  
    FROM test_select ORDER BY max DESC;
    

    From the other hand it works as well:

    SELECT object_id, MAX(event_timestamp) as max_event_timestamp
    FROM test_select 
    GROUP BY object_id 
    ORDER BY max_event_timestamp DESC;
    

提交回复
热议问题