I have 4 tables, as below.
Table: Class
ClassID | ClassSTD
--------------------------------
1 | STD-1
2 | STD-2
3 | STD-3
4 | STD-4
Table: Section
SectionId | SectionName | ClassId
--------------------------------------------
1 | sec-A | 1
2 | sec-B | 1
3 | sec-C | 1
4 | sec-A | 2
5 | sec-B | 2
6 | sec-C | 2
7 | sec-A | 3
Table: Subject
subjectId | subjectName
------------------------------------
1 | Art
2 | Music
3 | Play
Table SubjectAllocationToClass
classId | sectionID | subjectId | type
-----------------------------------------------------------------------
1(STD-1) | 1(sec-A) | 1(Art) | main
1(STD-1) | 2(sec-B) | 1(Art) | main
1(STD-1) | 3(sec-C) | 1(Art) | optional
1(STD-1) | 1(sec-A) | 2(Music) | main
1(STD-1) | 2(sec-B) | 2(Music) | optional
Above table "SubjectAllocationToClass" shows distribution of two type of subject (Main and optional) to section for class.
Need All Class irrespective of section or subjectAllocation Need All Section irrespective of subjectAllocation
How I can achieve below result from SELECT statement?
classSTD | sectionName | Main subjectName | Optional subjectName
-----------------------------------------------------------------------------
STD-1 | sec-A | Art, Music |
STD-1 | sec-B | Art | Music
STD-1 | sec-C | | Art
STD-3 | sec-A | |
STD-4 | | |
You can use GROUP_CONCAT()
along with CASE
expression to have a conditional grouping like below
select c.ClassID, s.sectionName,
xx.`Main subjectName`,
xx.`optional subjectName`
from Class c
join Section ss on c.ClassID = ss.ClassID
join (
select sa.sectionID,
group_concat(case when sa.type = 'main' then s.subjectName else null end) as `Main subjectName`,
group_concat(case when sa.type = 'optional' then s.subjectName else null end) as `optional subjectName`
from SubjectAllocationToClass sa
join Subject s on sa.subjectId = s.subjectId
group by sa.subjectId ) xx on ss.SectionId = xx.SectionId;
select
ClassSTD as ClassSTD,
sectionname AS SectionName,
COALESCE(GROUP_CONCAT(CASE WHEN sac.type = 'main' THEN subjectName END), '') as 'Main subjectname',
COALESCE(GROUP_CONCAT(CASE WHEN sac.type = 'optional' THEN subjectName END), '') as 'Optional subjectname'
FROM SubjectAllocationToClass sac
JOIN Class c ON c.classid = sac.classid
JOIN Section sc ON sc.sectionid = sac.sectionid
JOIN Subject sj ON sj.subjectid = sac.subjectid
GROUP BY ClassSTD, SectionName;
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.