I have the following original table
What I want is to retrieve latest history_id with distinct new_id. As follow:
I found this distinct_but_only_one_column but it only contains how to retrieve distinct one column. Please help me out.
I have the following original table
What I want is to retrieve latest history_id with distinct new_id. As follow:
I found this distinct_but_only_one_column but it only contains how to retrieve distinct one column. Please help me out.
This will work, assuming your table is named x
:
select * from x
where history_id in (
select max(history_id) from x group by news_id
);
Output:
history_id | news_id | news_headline
------------+---------+--------------------
1 | 5 | My test Headline
13 | 7 | My test Headline
3 | 4 | New Headline
4 | 6 | History Headline
This also works (and is simpler):
select distinct on (news_id) *
from x
order by news_id, history_id desc;
(but this never feels "right" to me)
Try using this,
select max(history_id),news_id,newsheadline from
table1 group by news_id,newsheadline
Instead of using distinct on
you can use a window function which is usually more flexible but a bit slower than using 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;