简体   繁体   中英

missing right pharenthesis, subquery error for finding population density

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

You can use the ROW_NUMBER analytic function so you do not need to query the tables twice:

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;

If you really did want to use your query then you cannot have an ORDER BY clause in the sub-query within an IN clause. What you probably want is to find the ROWID for the maximum year and population and correlating on the code primary key:

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
       )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM