Postgres:不同但仅适用于一列和最新一列

时间:2014-08-15 05:12:50

标签: postgresql select distinct-on

我有以下原始表

orginal table

我想要的是使用不同的new_id检索最新的history_id。如下:

desired result

我发现了这个distinct_but_only_one_column,但它只包含了如何检索不同的一列。请帮帮我。

3 个答案:

答案 0 :(得分:3)

这将起作用,假设您的表名为x

select * from x
where history_id in (
   select max(history_id) from x group by news_id
);

输出:

 history_id | news_id |      news_headline       
------------+---------+--------------------
          1 |       5 | My test Headline
         13 |       7 | My test Headline
          3 |       4 | New Headline
          4 |       6 | History Headline

这也有效(并且更简单):

select distinct on (news_id) *
from x
order by news_id, history_id desc;

(但这从未感觉到#34;对我来说是对的)

答案 1 :(得分:0)

尝试使用它,

select max(history_id),news_id,newsheadline from 
table1 group by news_id,newsheadline

答案 2 :(得分:0)

您可以使用窗口函数,而不是使用distinct on,这通常比使用distinct on

更灵活但速度稍慢
select history_id, news_id, news_headline
from (
   select history_id, news_id, news_headline,
          row_number() over (partition by news_id order by history_id desc) as rn
   from the_table
) t
where rn = 1
order by history_id;