Select Count with Union

Asked

Viewed 225 times

1

Hello. I need to make a mysql query with 3 Count in the same table. I got my results to appear below each other in the same column, but I need them to be in different columns.

It goes like this: I need to show the number of students enrolled in ballet classes, the number of students enrolled in jazz classes and the number of students enrolled in both classes. From the beginning of the year until today (04/09).

My query:

select count(*) as quantidade_ballet from alunos 
where datamatricula>='2015-01-01%' and datamatricula<='2015-09-04%'
and (indballet=1 and indjazz=0)

union(select count(*) as quantidade_jazz from alunos
where datamatricula>='2015-01-01%' and datamatricula<='2015-09-04%'
and (indjazz=1 and indballet=0))

union(select count(*) as quantidade from alunos
where datamatricula>='2015-01-01%' and datamatricula<='2015-09-04%'
and (indjazz=1 and indballet=1));

PS: indballet and indjazz are the boolean indicators of which class the student is enrolled.

Can anyone help me ? Thank you.

1 answer

2


select 
count(*) as quantidade_ballet,
(select count(*) from alunos
    where datamatricula>='2015-01-01%' and datamatricula<='2015-09-04%'
    and (indjazz=1 and indballet=0)) as quantidade_jazz,

 (select count(*) from alunos
    where datamatricula>='2015-01-01%' and datamatricula<='2015-09-04%'
    and (indjazz=1 and indballet=1)) as quantidade

     from alunos 
    where datamatricula>='2015-01-01%' and datamatricula<='2015-09-04%'
    and (indballet=1 and indjazz=0);

to improve performance use Count(id) instead of Count(*)

  • 1

    Beauty @Guerra, it worked! Thank you!!!

  • Sync and corrections by n17t01

Browser other questions tagged

You are not signed in. Login or sign up in order to post.