我正在尝试解决这个问题。
返回一个表,该表列出了语言和发言者人数,但仅包括具有> 200,000,000发言者的语言?根据发言人数量将这些结果从高到低排序
这是我的代码:
SELECT
Language,
Percentage / 100 AS 'Percentage',
SUM(Population) AS Population,
Population * Percentage AS 'Speakers'
FROM
language
GROUP BY
Language
HAVING
Speakers > 200000000;
有人可以帮我吗?
答案 0 :(得分:0)
您可以在下面尝试使用演说者的计算表达式进行
SELECT
Language,
Percentage/100 AS 'Percentage',
SUM(Population) AS Population,
SUM(Population)*(Percentage/100) AS 'Speakers'
FROM language
GROUP BY Language
HAVING SUM(Population)*(Percentage/100)> 200000000
ORDER BY SUM(Population)*(Percentage/100) DESC
答案 1 :(得分:0)
请勿对列别名使用单引号。那真是个坏习惯。仅对字符串和日期常量使用单引号。
SQL(通常)允许您在ORDER BY
中引用列别名。有些数据库还允许您在HAVING
子句中引用它们-但不是全部。
我不确定Percentage
应该做什么。它应该在GROUP BY
中。在其他情况下,Percentage
应该是聚合计算的一部分:
SELECT Language,
SUM(Percentage * Population / 100) / SUM(Population) AS Percentage,
SUM(Population) AS Population,
SUM(Population * Percentage/100) AS Speakers
FROM language
GROUP BY Language
HAVING SUM(Population*Percentage/100.0) > 200000000
ORDER BY Speakers DESC;
请注意,某些数据库执行整数除法,因此99/100 = 0,而不是0.99。因此,我会这样做:
SELECT Language,
SUM(Percentage * Population / 100.0) / SUM(Population) AS Percentage,
SUM(Population) AS Population,
SUM(Population*Percentage/100.0) AS Speakers
FROM language
GROUP BY Language
HAVING SUM(Population*Percentage/100.0) > 200000000
ORDER BY Speakers DESC;