【问题标题】:How to get distinct results with max of a field如何使用最大字段获得不同的结果
【发布时间】:2018-11-08 22:47:22
【问题描述】:

我有一个问题:

select distinct(donorig_cdn),cerhue_num_rfa,max(cerhue_dt) from t_certif_hue 


 group by donorig_cdn,cerhue_num_rfa 


 order by donorig_cdn 

它返回了一些具有不同 cerhue_num_rfa 的重复 ID

我如何只为与日期最大值 (cerhue_dt) 匹配的 cerhue_num_rfa 的重复 id 返回一行......并且最后只有 10 个结果而不是 15 个?

【问题讨论】:

  • distinctNOT 一个函数。它是一个适用于选择列表中的 all 列的运算符。 distinct (a), b, cdistinct a,(b),cdistinct a,b,(c) 完全相同。话虽如此:您可能想要distinct on ()postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
  • 看起来像一个经典的top-n-per-group问题。
  • 虽然对于这个小问题来说并不重要,但最好的做法是在问题中包含表定义和示例数据。因此,每个人都可以重现您的行为并测试他们的解决方案。

标签: postgresql max distinct


【解决方案1】:

Postgres 有 SELECT DISTINCT ON 来救援。它只返回为给定列的每个值找到的第一行。因此,您所需要的只是一个确保最新条目排在第一位的订单。无需分组。

SELECT DISTINCT ON (donorig_cdn) donorig_cdn,cerhue_num_rfa,cerhue_dt
  FROM t_certif_hue 
  ORDER BY donorig_cdn, cerhue_dt DESC;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2021-08-02
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2015-01-08
    相关资源
    最近更新 更多