SQL Pivot Help: I have three tables as follows: Class Table:
ID Name
1 N1
2 N2
3 N3
Flags Table:
ID ClassID Flags
1 1 F1
1 1 F2
1 2 F3
1 3 F1
1 3 F3
Session Table:
ID ClassID Session
1 1 S1
2 1 S2
3 1 S3
4 2 S2
5 2 S5
6 3 S1
6 开发者_运维技巧 3 S2
Now I need to create a view something like this:
Class View:
ID Name Flags Session
1 N1 F1,F2 S1,S2,S3
2 N2 F3 S2,S5
3 N3 F1,F3 S1,S2
The best approach would be to create the comma separated lists in the presentation layer of the client. You can join the tables together like:
select
class.id
, class.name
, flags.flags
, session.session
from class
left join flags on flags.classid = class.id
left join session on session.classid = class.id
Although databases are not meant to format data, most databases support some way of generating comma separated lists. For example, in MySQL, you can use group_concat
:
select
class.id
, class.name
, group_concat(flags.flags separator ',')
, group_concat(session.session separator ',')
from class
left join flags on flags.classid = class.id
left join session on session.classid = class.id
group by class.id, class.name
If you're using another DMBS, please add it to your question.
From this SO question, I figured out the following:
select fs.ClassId
, fs.ClassName
, LEFT(fs.Flags, LEN(fs.Flags) - 2) as Flags
, LEFT(fs.Sessions, LEN(fs.Sessions) - 2) as Sessions
from (
select c.Id as ClassId
, c.[Name] as ClassName
, (
select Flags + N', ' as [text()]
from FlagsTable
where ClassId = c.Id
FOR XML PATH (N'')
) as Flags
, (
select Session + N', ' as [text()]
from SessionTable
where ClassId = c.Id
FOR XML PATH (N'')
) as Sessions
from ClassTable c
) fs
精彩评论