1

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
DAK
  • 1,395
  • 4
  • 22
  • 35
  • 1
    PIVOT is one thing that just about every database implements differently. Without specifying the database and version, you'll most likely get few if any responses to this question. – KM. May 26 '10 at 14:56

2 Answers2

2

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.

Andomar
  • 232,371
  • 49
  • 380
  • 404
  • 2
    For SQL Server, the usual approach is a `for xml` trick, see http://blog.shlomoid.com/2008/11/emulating-mysqls-groupconcat-function.html – Andomar May 26 '10 at 16:06
1

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
Community
  • 1
  • 1
Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162