【问题标题】:Postgres: Distinct but only for one column and latest onePostgres:不同但仅适用于一列和最新一列
【发布时间】:2014-08-15 05:12:49
【问题描述】:

我有以下原始表格

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

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

【问题讨论】:

  • 检查您的第一个结果行?我认为它是错误的,否则显示你的逻辑
  • news_headline 的值在您显示所需输出的位置是否正确?我不确定我是否了解这些相关性。
  • 您在寻找DISTINCT ON吗?

标签: postgresql select distinct-on


【解决方案1】:

假设您的表名为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;

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

【讨论】:

    【解决方案2】:

    您可以使用窗口函数代替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;
    

    【讨论】:

      【解决方案3】:

      试试这个,

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

      【讨论】:

      • 只有当news_headline 是所有news_id 的相同值时才有效(可能是,但又可能不是)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 2014-10-11
      • 2017-11-19
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多