我有以下表格:
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
现在我想编写一个返回以下结果的查询:
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
此外,tblMail
是动态的..它可以有更多行。因此,如果将来我添加列应该在结果中显示的新行。
任何帮助将不胜感激。感谢
答案 0 :(得分:1)
你可以像这样动态构建sql:
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)
我甚至在这里添加了一个SQL Fiddle示例:http://sqlfiddle.com/#!3/0c0ad/8/0