我在单个表格中有关于房地产数据的以下信息:
PropertyID
OwnerName
OwnershipDate
PropertyAddress
中找到示例数据
我要pivot
将结果转换成所需的输出,如下所示
PropertyID OwnerName OwnershipDate OwnerName OwnershipDate
0121320100011 RIVERA VICTOR 2018-02-06 00:00:00.0000000 RIVERA RAQUEL 2018-02-06 00:00:00.0000000
我希望根据每个PropertyID
找到的所有者数量来动态调整列数。
目前为止的努力如下:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.OwnerName)
FROM owners_rec c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select account,ownername
from owners_rec
) x
pivot
(
max(account)
for ownername in (' + @cols + ')
) p '
execute(@query)
总是喜欢伸出援助之手:)