我正在处理一个简单的消息数据库。

 id           | integer
 parent_id    | integer
 msg          | character varying(140)
 create_dte   | numeric(10,0)

Messages have a parent_id of -1 (top-level) or the id of another message.I want to return most recent top-level messages--most recent defined asrecent create_dte of the parent or any of its children.

Here is my query:

select (case when parent_id != -1 then parent_id else id end) as mid, create_dte
from messages
order by create_dte desc

我的结果是这样的:
中|创建
------+----------------------
5655 | 1333906651
5462 | 1333816235
5496 | 1333686356
5157 | 1333685638
676 | 1333648764
5493 | 1333648630
724 | 1333641318
5402 | 1333470056
5397 | 1333468897
5396 | 1333468378
3640 | 133304212
3434 | 133330366
2890 | 1333293369
4958 | 1333288239
4899 | 1333287641
5203 | 1333287298
4899 | 1333287275
4899 | 1333285593
如何在保持创建类型的同时消除结果中的重复项?
我试过各种不同的方法,但总是搞不清分类。
我需要的是:
中|创建
------+----------------------
5655 | 1333906651
5462 | 1333816235
5496 | 1333686356
5157 | 1333685638
676 | 1333648764
5493 | 1333648630
724 | 1333641318
5402 | 1333470056
5397 | 1333468897
5396 | 1333468378
3640 | 133304212
3434 | 133330366
2890 | 1333293369
4958 | 1333288239
4899 | 1333287641
5203 | 1333287298
(最后两行未返回为4899,结果中已出现更新的create_dte。)
谢谢

最佳答案

请尝试以下操作:

select (case when parent_id != -1 then parent_id else id end) as mid, max(create_dte )
from messages
group by case when parent_id != -1 then parent_id else id end
order by max(create_dte) desc;

关于sql - PostgreSQL:在单列上选择不同的值,而在另一列上排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10083757/

10-11 01:38