I'm trying to write a query that gets get the population density of which we find by taking the population and dividing it by the area. I have made a subquery
Select max(p.pop)
from state s
left join statepop p
on p.code = s.code
group by s.name
Order by max(p.year)
That gets the most recent year, I thought I could take this and drop it into my parent query, and I've tried in two different ways, but I get an error saying "missing right parenthesis." I've read up on things and believe it to be a syntax error but I'm not sure where I'm going wrong. Is there a better way to do this, or can someone point out where in my query it's causing it to throw this error?
select s.name, round( p.population / s.area, 2)
from state s
left join statepop p
on p.code = s.code
where p.pop in (
Select max(p.pop)
from state s
left join statepop p
on p.code = s.code
group by s.name
Order by max(p.year)
)
select s.name, round( (
Select max(p.pop)
from state c
left join statepop p
on p.code = s.code
group by s.name
Order by max(p.year) DESC
)/ s.area, 2)
from state s
inner join statepop p
on p.code= s.code;
Tables: "state" Code is our key that is unquie for each state
| name | code | area |
| ------------ | ------------ | ------------ |
| Ohio | OH | 50 |
| Wisconsin | WI | 100 |
"statepop"
| code | Year | pop |
| ------------ | ------------ | ------------ |
| OH | 1998 | 10000 |
| OH | 2000 | 1000 |
| OH | 1998 | 6000 |
| OH | 1978 | 8000 |
| WI | 1999 | 2000 |
| WI | 2000 | 20000 |
| WI | 2000 | 5000 |
1条答案
按热度按时间h43kikqp1#
您可以使用
ROW_NUMBER
分析函数,这样就不需要查询两次表:如果确实要使用查询,则不能在
IN
子句内的子查询中使用ORDER BY
子句。您可能需要查找最大年份和人口的ROWID
,并与code
主键关联: