Skip to content
Advertisement

SQL subquery for function count

The first column is the name of the locality,the second column is the number of voters in every locality.. my problem is on the third column because im trying to count voters that are unemployment but is counting all voters.sorry for my english.

select l.nombre as "Nombre",count(v.dni) as "Votantes",
(select count(v.dni) from localidades l,votantes v
where v.localidad=l.idlocalidad and v.situacionlaboral='Parado') as "Parados"
from votantes v,localidades l
where v.localidad=l.idlocalidad 
group by l.nombre;

this is the out:

"Nombre" "Votantes" "Parados"

Sevilla    3          4
Baena      1          4
Córdoba    3          4
Montilla   1          4
Madrid     3          4
Utrera     3          4
Carmona    1          4
Badalona   1          4
Getafe     1          4

Advertisement

Answer

Try this:

select l.nombre as "Nombre"
       , count(v.dni) as "Votantes"
       , sum(case when situacionlaboral = 'Parado' then 1
              else 0
              end) as "Parados"
from votantes v
join localidades l on v.localidad=l.idlocalidad 
group by l.nombre;

When you join two tables please do it like this:

from localidades l 
join votantes v on v.localidad = l.idlocalidad 

And not like this:

from localidades l,votantes v
where v.localidad=l.idlocalidad
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement