Return records distinct on one column but order by another column

醉酒当歌 提交于 2019-12-04 19:44:37
Erwin Brandstetter

DISTINCT ON

If you use DISTINCT ON, you need a subquery for that:

SELECT *
FROM  (
   SELECT DISTINCT ON (conversation_id) *
   FROM   message t
   ORDER  BY conversation_id, created_at DESC
   ) sub
ORDER BY created_at DESC;

The order in the subquery must agree with the columns in the DISTINCT ON clause, so you must wrap it in an outer query to arrive at your desired sort order.

Alternative with row_number()

Similar story, you need a subquery as well:

SELECT id, sender_id, receiver_id, conversation_id, subject, body, created_at
FROM  (
   SELECT *, row_number() OVER (PARTITION BY conversation_id
                                ORDER BY created_at DESC) AS rn
   FROM   message t
   ) sub
WHERE  rn = 1
ORDER  BY created_at DESC;

Also probably slower.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!