2

我有以下原始表格

原始表

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

期望的结果

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

4

3 回答 3

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;

(但这对我来说从来没有“正确”的感觉)

于 2014-08-15T05:38:19.803 回答
0

试试用这个,

select max(history_id),news_id,newsheadline from 
table1 group by news_id,newsheadline
于 2014-08-15T05:37:15.997 回答
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;
于 2014-08-15T05:37:27.747 回答