给出这里的两个示例表:
门票表
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
我怎样才能得到这样的 View :
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 执行此操作。执行数据透视表时,您可以通过以下两种方式之一进行操作:使用静态数据透视表(您将对要转换的行进行编码)或动态数据透视表(将在运行时创建列列表):
静态枢轴(参见SQL Fiddle for 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
或者您可以使用动态枢轴(参见 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)
两个查询将返回相同的结果。
关于SQL:动态 View ,其列名称基于源表中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10986031/