我有以下原始表
我想要的是使用不同的new_id检索最新的history_id。如下:
我发现了这个distinct_but_only_one_column,但它只包含了如何检索不同的一列。请帮帮我。
答案 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;