【发布时间】: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() 声明解决我的问题,但无法让它工作。有什么解决方法吗?
【问题讨论】:
-
@MikeOrganek 我不这么认为。您发送的那个使用 ORDER BY,我的问题是 max 函数的分组。我不认为解决方案是一样的
标签: sql postgresql group-by max greatest-n-per-group