我的查询如下:
SELECT CO.CONTINENT, FLOOR(AVG(CI.POPULATION))
FROM CITY CI INNER JOIN COUNTRY CO
ON CI.COUNTRYCODE = CO.CODE
GROUP BY CO.CONTINENT;
现在,我希望得到相同的结果,但不使用Group by,因为我正在寻找学习目的的替代方案。我确信这可以使用子查询来实现,但我无法做到。
我尝试过以下方法:
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;
答案 0 :(得分:3)
试试这个:
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
在幕后实现的,但我不知道如何在不执行此操作的情况下仅报告每个大陆一次。
答案 1 :(得分:0)
我不是真的推荐这种方法,但你可以这样做:
SELECT DISTINCT CO.CONTINENT, FLOOR(AVG(CI.POPULATION))
FROM CITY CI INNER JOIN
COUNTRY CO
ON CI.COUNTRYCODE = CO.CODE;