我有一个表[world],其中包含字段(名称,人口,GDP,面积等)。我可以得到像这样的桌子
World
name Total Populat.. Pop Density/KM
China 19.18 142.3
India 17.51 393.6
USA 4.47 32.4
Indonesia 3.54 132.4
Brazil 2.85 23.8
Pakistan 2.64 213.2
Nigeria 2.51 193.2
Bangladesh 2.20 1060.9
Russia 2.05 8.5
Japan 1.79 336.3
使用代码。
SELECT name,
ROUND (population/(SELECT sum(population) FROM world )* 100,2 ) as 'Total Population',
ROUND (population/area ,1) as 'Pop Density/KM'
FROM world
ORDER BY 2 Desc LIMIT 10
我正在尝试使用此代码
SELECT name,
ROUND (population/(SELECT sum(population) FROM world )* 100,2 ) as 'Total Population',
ROUND (population/area ,1) as 'Pop Density/KM'
FROM world
ORDER BY 2 DESC LIMIT 10, 3
这样我就可以得到一个表格,该表格按人口显示前10行,但按第3列的顺序对其进行排序。简而言之,我希望只能显示这些记录(如上表所示),但要根据Pop Popsity / KM Descending进行合理排序。我没有得到想要的结果
答案 0 :(得分:2)
您需要使用子查询。但是不要对列别名使用单引号!仅对字符串和日期常量使用单引号。
所以:
SELECT *
FROM (SELECT name,
ROUND(population/(SELECT sum(population) FROM world) * 100, 2) as "Total Population",
ROUND(population/area, 1) as "Pop Density/KM"
FROM world
ORDER BY "Total Population" DESC
LIMIT 10
) w
ORDER BY "Pop Density/KM";
在MariaDB中,您还可以使用反引号作为转义字符。实际上,我建议重命名这些列,以使它们根本不需要转义。
答案 1 :(得分:1)
您需要将其包装到另一个选择中,并使用双引号,如Gordon Linoff在其答案中所述。
SELECT *
FROM (
SELECT name,
ROUND (population/(SELECT sum(population) FROM world )* 100,2 ) as "Total Population",
ROUND (population/area ,1) as "Pop Density/KM"
FROM world
ORDER BY 2 DESC
LIMIT 10
)
ORDER BY "Pop Density/KM"