【问题标题】:SQL MAX funtion where not all atributes are in the group bySQL MAX 函数,其中并非所有属性都在 group by
【发布时间】:2021-03-03 19:28:37
【问题描述】:

所以我目前的问题是我有两个看起来像这样的表:

table1(name, num_patient, quant, inst)
table2(inst_name, num_region)

我想在哪里找到每个区域数量最多的患者。

我首先想到做这样的事情:

SELECT num_region, num_patient, MAX(quant)
FROM
  (SELECT num_patient, quant, num_region
  FROM table1
  INNER JOIN table2
  ON table1.inst = table2.inst_name) AS joined_tables
GROUP BY num_region;

但这不起作用,因为num_patient 必须在GROUP BY 上(这样它就不再按区域返回最大值)或者我必须从SELECT 中删除它(也不起作用,因为我需要每个患者的姓名)。我试图用WHERE quant = MAX() 声明解决我的问题,但无法让它工作。有什么解决方法吗?

【问题讨论】:

标签: sql postgresql group-by max greatest-n-per-group


【解决方案1】:

这是我链接的 DISTINCT ON 问题的副本。

SELECT distinct on (num_region) num_patient, quant, num_region
  FROM table1
  INNER JOIN table2
  ON table1.inst = table2.inst_name
ORDER BY num_region, quant desc

【讨论】:

    【解决方案2】:

    使用DISTINCT ON:

    SELECT DISTINCT ON (num_region), num_patient, quant, num_region
    FROM table1 t1 JOIN
         table2 t2
         ON t1.inst = t2.inst_name
    ORDER BY num_region, quant DESC;
    

    DISTINCT ON 是一个方便的 Postgres 扩展。它根据ORDER BY 中的顺序,为SELECT 中指定的每个键返回一行。

    作为一个扩展,并不是所有的数据库都支持这个功能——甚至是从 Postgres 派生的数据库。传统方法会使用ROW_NUMBER():

    SELECT t.*
    FROM (SELECT num_patient, quant, num_region,
                 ROW_NUMBER() OVER (PARTITION BY num_region ORDER BY quant DESC) as seqnum
          FROM table1 t1 JOIN
               table2 t2
               ON t1.inst = t2.inst_name
         ) t
    WHERE seqnum = 1;
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多