Error subquery uses ungrouped (columns correlation)

Posted on

Question :

Recently I tried to create a query to obtain some statistical data, but I got this error:

subquery uses ungrouped column “vegetacionpotencial.ident” from outer query

select 
  veg_pot
  , sum(hauvg)
  ,(
     select 
       sum(hadef) 
     from tematica.vegetacionpotencial v, tematica.deforestacion d 
       join estados on (vegetacionpotencial.ident=estados.ident) 
     where 
       st_covers(v.geom,d.geom) and estado = 'Yucatán'
   ) 
from tematica.vegetacionpotencial
  join estados on (vegetacionpotencial.ident=estados.ident)
where 
  estado = 'Yucatán' 
group by 
  veg_pot

Answer :

Your original query formatted but otherwise unchanged:

SELECT veg_pot, sum(hauvg)
     ,(SELECT sum(hadef) 
       FROM   tematica.vegetacionpotencial v
            , tematica.deforestacion d 
       JOIN   estados ON (vegetacionpotencial.ident = estados.ident) 
       WHERE  st_covers(v.geom, d.geom)
       AND    estado = 'Yucatán') 
FROM   tematica.vegetacionpotencial
JOIN   estados ON (vegetacionpotencial.ident = estados.ident)
WHERE  estado = 'Yucatán' 
GROUP  BY veg_pot;

Since you added the column alias v to tematica.vegetacionpotencial in the correlated subquery, the original table name is not visible any more. To refer3ence the table (like it seems you want to) you must use the visible alias v.

After checking visible identifiers in the inner query, Postgres extends the scope to the next outer query level and finds vegetacionpotencial there. Howev er, the column ident is not grouped in outer query, which leads to the logic error you got:

subquery uses ungrouped column “vegetacionpotencial.ident” from outer query

You can fix the error, but the query is still no good:

SELECT veg_pot, sum(hauvg)
     ,(SELECT sum(hadef) 
       FROM   tematica.vegetacionpotencial v1
       JOIN   estados e ON v1.ident = e.ident
            , tematica.deforestacion d 
       WHERE  st_covers(v.geom, d.geom)
       AND    estado = 'Yucatán') 
FROM   tematica.vegetacionpotencial v
JOIN   estados ON vegetacionpotencial.ident = estados.ident
WHERE  estado = 'Yucatán' 
GROUP  BY veg_pot, v.geom;

Proper information is missing, but going out on a limb, my educated guess is you might want something like this instead:

SELECT veg_pot, sum(hauvg) AS sum_hauvg
    , (SELECT sum(hadef)
       FROM   tematica.deforestacion d 
       WHERE  st_covers(v.geom, d.geom)) AS sum_hadef
FROM   estados e
JOIN   tematica.vegetacionpotencial v USING (ident)
WHERE  e.estado = 'Yucatán'
GROUP  BY veg_pot, v.geom;

Leave a Reply

Your email address will not be published. Required fields are marked *