给定两个示例表:
门票表
ID User Description 0 James This is a support ticket 1 Fred This is a ticket too
属性表
ID TicketID Label Value 0 0 Engineer Scott 1 1 Engineer Dale 2 0 Manu Dell 3 1 Manu HP 4 0 OS Windows 5 1 OS Linux
我如何获得这样的视图:
ID User Description Engineer Manu OS 1 James This is a support ticket Scott Dell Windows 2 Fred This is a ticket too Dale HP Linux
重要的是要注意,属性表并不总是相同的。一些“票证”可能具有其他人没有的属性。
这有可能吗?
您可以使用PIVOT执行此操作。在执行PIVOT时,可以使用以下两种方法之一进行操作:使用“静态数据透视表”(将对行进行编码)或“动态数据透视表”将在运行时创建列列表:
静态数据透视表(请参见SQL Fiddle中的Demo):
select id, [user], [engineer], [manu], [OS] from ( select t.id , t.[user] , p.ticketid , p.label , p.value from tickets t inner join properties p on t.id = p.ticketid ) x pivot ( min(value) for label in ([engineer], [manu], [OS]) ) p
或者,您可以使用Dynamic Pivot(请参见SQL Fiddle for Demo):
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); select @cols = STUFF((SELECT distinct ',' + QUOTENAME(p.label) from tickets t inner join properties p on t.id = p.ticketid FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT id, [user], ' + @cols + ' from ( select t.id , t.[user] , p.ticketid , p.label , p.value from tickets t inner join properties p on t.id = p.ticketid ) x pivot ( min(value) for label in (' + @cols + ') ) p ' execute(@query)
这两个查询将返回相同的结果。