【发布时间】:2021-02-06 21:38:12
【问题描述】:
问题笼统地说:我需要从一个表中选择一个引用另一个表中重复次数最多的值的值。
表具有以下结构: screenshot screenshot2
问题是找到与它相关的运动员的成绩最多的国家。
首先,INNER JOIN 表在结果和国家/地区之间建立关系
SELECT competition_id, country FROM result
INNER JOIN sportsman USING (sportsman_id);
然后,我计算每个国家出现的时间
SELECT country, COUNT(country) AS highest_participation
FROM (SELECT competition_id, country FROM result
INNER JOIN sportsman USING (sportsman_id))
GROUP BY country
;
得到了这个screenshot3
现在感觉我离解决方案只有一步之遥)) 我想可以再使用一个 SELECT FROM (SELECT ...) 和 MAX() 但我无法结束它?
ps: 我通过将这样的查询加倍来做到这一点,但如果有数百万行,我觉得效率太低了。
SELECT country
FROM (SELECT country, COUNT(country) AS highest_participation
FROM (SELECT competition_id, country FROM result
INNER JOIN sportsman USING (sportsman_id)
) GROUP BY country
)
WHERE highest_participation = (SELECT MAX(highest_participation)
FROM (SELECT country, COUNT(country) AS highest_participation
FROM (SELECT competition_id, country FROM result
INNER JOIN sportsman USING (sportsman_id)
) GROUP BY country
))
我也是用视图来做的
CREATE VIEW temp AS
SELECT country as country_with_most_participations, COUNT(country) as country_participate_in_#_comp
FROM(
SELECT country, competition_id FROM result
INNER JOIN sportsman USING(sportsman_id)
)
GROUP BY country;
SELECT country_with_most_participations FROM temp
WHERE country_participate_in_#_comp = (SELECT MAX(country_participate_in_#_comp) FROM temp);
但不确定这是否是最简单的方法。
【问题讨论】:
标签: sql oracle count sql-order-by inner-join