简体   繁体   中英

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

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

If you want the total votes, use window functions:

select l.nombre, count(*) as Votantes,
       sum(count(*)) over () as parados
from votantes v join
     localidades l
     on v.localidad = l.idlocalidad 
group by l.nombre;

Also learn to use proper, explicit, standard JOIN syntax.

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