Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Query:Not able to group data from different tables

I am not able to resolve this query.

Tables are:

tblStandard1students
tblStandard2students
tblStandard3students     
tblCandidateinfo

tblStandard1students, tblStandard2students and tblStandard3students tbl contain information about students enrolled in standard 1,2 and 3.

tblStandars1students

Candid  admitted
  1        Y
  2        N
  3        Y


tblCandidateinfo

Candid  gender Division
  1       M      1
  2       F      2

and so on...

Now I want the table like this

Gender  Students(Standard1)  Students(Standard2)  Students(Standard3)
------------------------------------------------------------------------
 Male           10                 20                      30    
 Female         10                 30                      40

I tried this but this does not give me error:

SELECT case when Gender='M' then 'Male' 
            when Gender='F' then 'Female' 
       END AS Gender,

( SELECT count(*)
 FROM tblStandard1students A
 where A.Candid=B.Candid
 ) AS Students(Standard1),

( SELECT count(*)
 FROM tblStandard2students A
    where A.Candid=B.Candid
) AS Students(Standard2),

( SELECT count(*)
 FROM tblStandard3students A
    where A.Candid=B.Candid
) AS Students(Standard3)


FROM tblCandidateinfo B
group by Gender
like image 995
user1274646 Avatar asked Nov 04 '22 03:11

user1274646


1 Answers

SQLFiddle demo

select 
case when Gender='M' then 'Male' 
            when Gender='F' then 'Female' 
      END AS Gender,
sum(T.std1) as [Students(Standard1)],
sum(T.std2) as [Students(Standard2)],
sum(T.std3) as [Students(Standard3)]
from
tblCandidateinfo as C

JOIN
(
select Candid, 1 as std1, 0 as std2, 0 as std3 
from tblStandars1students
union all
select Candid, 0 as std1, 1 as std2, 0 as std3 
from tblStandars2students
union all
select Candid, 0 as std1, 0 as std2, 1 as std3 
from tblStandars3students
) as T on (C.Candid=T.Candid)

GROUP BY GENDER
like image 119
valex Avatar answered Nov 12 '22 17:11

valex