sql - PostgreSQL:在对另一列进行排序时在单列上选择不同的值

标签 sql postgresql distinct

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

 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 as recent 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

我的结果是这样的:

 mid  | create_dte 
------+----------------------
 5655 |           1333906651
 5462 |           1333816235
 5496 |           1333686356
 5157 |           1333685638
  676 |           1333648764
 5493 |           1333648630
  724 |           1333641318
 5402 |           1333470056
 5397 |           1333468897
 5396 |           1333468378
 3640 |           1333304212
 3434 |           1333300366
 2890 |           1333293369
 4958 |           1333288239
 4899 |           1333287641
 5203 |           1333287298
 4899 |           1333287275
 4899 |           1333285593

如何在保持 create_dte 类型的同时消除结果中的重复项? 我试过 distinct 和 distinct on 但总是失去排序。

这是我需要的:

mid  | create_dte 
------+----------------------
 5655 |           1333906651
 5462 |           1333816235
 5496 |           1333686356
 5157 |           1333685638
  676 |           1333648764
 5493 |           1333648630
  724 |           1333641318
 5402 |           1333470056
 5397 |           1333468897
 5396 |           1333468378
 3640 |           1333304212
 3434 |           1333300366
 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/

相关文章:

sql - Oracle 中动态求和和分组

sql - 我怎样才能做一个不同的总和?

MySQL查询将规范化数据转换为单行

postgresql - 优化 postgres 相似性查询(pg_trgm + gin 索引)

R: "stack"列在彼此之上

sql - 使用具有空值的默认约束?

ruby-on-rails - ActiveRecord::QueryCache#call slow on Heroku with pg:backups

c++ - 有效地遍历数据库行(libpqxx),为结构分配值

distinct - Linq 到 NHibernate Distinct() "Expression type not supported"错误

matlab - 使轴与其他网格不同