我有一个查询,如下所示:
SELECT CO.CONTINENT, FLOOR(AVG(CI.POPULATION))
FROM CITY CI INNER JOIN COUNTRY CO
ON CI.COUNTRYCODE = CO.CODE
GROUP BY CO.CONTINENT;
现在,我想获得相同的结果,但不使用分组依据,因为我正在寻找学习的替代方案。我敢肯定这可以使用子查询来实现,但是我做不到。
我尝试了以下方法:
SELECT CO.CONTINENT,
( SELECT FLOOR(AVG(CI2.POPULATION)) FROM CITY CI2 WHERE CI2.COUNTRYCODE = CO.CODE )
FROM CITY CI INNER JOIN COUNTRY CO
ON CI.COUNTRYCODE = CO.CODE;
要么
SELECT CO.CONTINENT, FLOOR(AVG(CI.POPULATION)) OVER(PARTITION BY CI.COUNTRYCODE)
FROM CITY CI INNER JOIN COUNTRY CO
ON CI.COUNTRYCODE = CO.CODE;
最佳答案
尝试这个:
SELECT DISTINCT
t.CONTINENT,
(SELECT FLOOR(AVG(c2.POPULATION)) FROM COUNTRY c1 INNER JOIN CITY c2
ON c1.CODE = c2.COUNTRYCODE WHERE c1.CONTINENT = t.CONTINENT) AS pop_avg
FROM COUNTRY t
顺便说一句,有时
DISTINCT
是在GROUP BY
的幕后实现的,但是我不知道如何不报告每个大洲一次。关于mysql - 如何在不使用group by的情况下获得此sql查询的相同结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49554035/