SQL MAX 函数,其中并非所有属性都在分组依据中

SQL MAX funtion where not all atributes are in the group by

所以我目前的问题是我有两个如下所示的表:

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 上(这样它就不再 return 按区域划分的最大值)或者我必须将其从 SELECT 中删除(也不起作用,因为我需要每个患者的姓名)。我试图用 WHERE quant = MAX() 语句解决我的问题,但无法让它工作。有什么解决方法吗?

这是我链接的 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

使用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 扩展。 returns SELECT 中指定的每个键一行,基于 ORDER BY 中的排序。

作为扩展,并非所有数据库都支持此功能——即使是从 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;