oracle 缺少右括号,查找人口密度时出现子查询错误

zdwk9cvp  于 2022-12-03  发布在  Oracle
关注(0)|答案(1)|浏览(110)

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 |

h43kikqp

h43kikqp1#

您可以使用ROW_NUMBER分析函数,这样就不需要查询两次表:

SELECT name,
       population_density
FROM   (
  SELECT s.name,
         ROUND(p.pop / s.area, 2) AS population_density,
         ROW_NUMBER() OVER (PARTITION BY s.code ORDER BY p.year DESC, p.pop DESC) AS rn
  FROM   state s
         LEFT JOIN statepop p
         ON p.code = s.code
)
WHERE  rn = 1;

如果确实要使用查询,则不能在IN子句内的子查询中使用ORDER BY子句。您可能需要查找最大年份和人口的ROWID,并与code主键关联:

select s.name,
       round( p.pop / s.area, 2)
from   state s
       left join statepop p
       on p.code = s.code
where  p.rowid IN (
         SELECT MAX(ROWID) KEEP (DENSE_RANK LAST ORDER BY year, pop)
         FROM   statepop px
         WHERE  s.code = px.code
       )

相关问题