我对SQL,MS Access& amp; PostgreSQL的。我很快就收到了这个查询任务。我首先阅读了基本的SQL语法,然后用逻辑编写了这个。不知怎的,我得到了这个SELECT
错误:
[]
SELECT
change_incoming_area AS Bodenfläche,
CASE
WHEN change_type_id = 2
AND (NOT cng.city_old_id=cng.city_new_id
AND EXTRACT(YEAR FROM cng.date_change) = EXTRACT(YEAR FROM tb_city_annual_population.population_year)) THEN
ROUND((cng.change_incoming_area/SELECT pop.city_area FROM tb_city_annual_population pop WHERE pop.city_id=cng.city_old_id)*100,2)
WHEN change_type_id = 2
AND (cng.city_old_id=cng.city_new_id
AND EXTRACT(YEAR FROM cng.date_change) = EXTRACT(YEAR FROM tb_city_annual_population.population_year)
AND cng.change_incoming_area<SELECT pop.city_area FROM tb_city_annual_population pop WHERE pop.city_id=cng.city_old_id) THEN
ROUND(((SELECT pop.city_area FROM tb_city_annual_population pop WHERE pop.city_id=cng.city_old_id AS origarea-cng.change_incoming_area)/origarea)*100,2)
WHEN change_type_id = 2
AND (cng.city_old_id=cng.city_new_id
AND EXTRACT(YEAR FROM cng.date_change) = EXTRACT(YEAR FROM tb_city_annual_population.population_year)
AND ((cng.change_incoming_area+SELECT pop.city_area FROM tb_city_annual_population pop WHERE pop.city_id=cng.city_old_id AS origarea3)/origarea3)*100>100) THEN
ROUND(((cng.change_incoming_area+SELECT pop.city_area FROM tb_city_annual_population pop WHERE pop.city_id=cng.city_old_id AS origarea2)/origarea2)*100,2)
ELSE 100
END
FROM tb_change cng;
答案 0 :(得分:1)
正如jarlh立即评论的那样:子查询必须在括号中。
这一行
ROUND( ( cng.change_incoming_area / select ... ) * 100, 2)
必须是
ROUND( ( cng.change_incoming_area / (select ...) ) * 100, 2)
或只是
ROUND( cng.change_incoming_area / (select ...) * 100, 2)
关于子查询本身:它当然必须只产生一个值。使用表名tb_city_annual_population
,我希望每个城市和每年都有一个记录。但是在你的where子句中,你只能按城市限制:
SELECT pop.city_area
FROM tb_city_annual_population pop
WHERE pop.city_id = cng.city_old_id
这不会给你几条记录(每年一条记录)吗?也许你想让它变成这样的东西:
SELECT pop.city_area
FROM tb_city_annual_population pop
WHERE pop.city_id = cng.city_old_id
AND pop.year = EXTRACT(YEAR FROM cng.date_change)
还有更多错误:
ROUND(((cng.change_incoming_area+SELECT pop.city_area FROM tb_city_annual_population pop
WHERE pop.city_id=cng.city_old_id AS origarea2)/origarea2)*100,2)
AS origarea2
是什么?您不能在表达式的中间使用AS。它应该是
ROUND((cng.change_incoming_area + (SELECT pop.city_area FROM tb_city_annual_population pop
WHERE pop.city_id = cng.city_old_id)) / origarea2 * 100, 2)
AS origarea3
和AS origarea
相同。
然后在
AND EXTRACT(YEAR FROM cng.date_change) =
EXTRACT(YEAR FROM tb_city_annual_population.population_year)) THEN
您引用tb_city_annual_population.population_year
,但未从tb_city_annual_population
中选择,则从tb_change
中选择。
然后从population_year
中提取年份。那么population_year
是约会吗?这个名字表明它是一个代表一年的整数。