简体   繁体   中英

Join three table and showing last table rows as columns

I have following tables:

tblData:

ID       Name         Email   
--------------------------------------   
1        TestName1    test@email.com
2        TestName2    test2@email.com
3        TestName3    test3@email.com

tblMail:

ID      Name             Content
------------------------------------------------
1       MailName1        Mail1 contents goes here
2       MailName2        Mail2 contents goes here
3       MailName3        Mail3 contents goes here

tblContacts:

ID      DataId      MailId
-------------------------------
1       1           1
2       1           2
3       3           1
4       3           3

Now i want to write a query that return following result:

ID      Name        Email             MailName1        MailName2        MailName3
----------------------------------------------------------------------------------
1       TestName1   test@email.com    True             True             False
2       TestName2   test2@email.com   False            False            False
3       TestName3   test3@email.com   True             False            True

Moreover, the tblMail is dynamic.. it can have more rows. so if in future i add new row that column should show in the result.

Any help will be appreciated. Thanks

You could build the sql dynamically like this:

declare @mailfields nvarchar(max) = N'',
        @mailfieldselect nvarchar(max) = N'',
        @sql nvarchar(max) = N'',
        @dlm nchar(1)= ''

select @mailfields=@mailfields + @dlm + N'[' + Name + N']', 
  @mailfieldselect = @mailfieldselect + @dlm + N'case when [' + Name + N'] = 0 then ''False'' else ''True'' end as ' + Name, 
  @dlm=',' 
from tblMail

select @sql ='select ID, Name, ' + @mailfieldselect + ' 
from (
  select d.ID, d.Name, m.Name as MailName 
  from tblData d 
  left join tblContacts c on d.Id=c.DataId 
  left join tblMail m on c.MailId=m.Id) f
pivot (count(MailName)
       for MailName in (' + @mailfields + ')) p'

exec (@sql)

I even added a SQL Fiddle example of this here: http://sqlfiddle.com/#!3/0c0ad/8/0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM