为了做到这一点,您需要考虑将 添加row_number()
到您的内部查询中。我正在使用row_number
withname
创建列name1
、name2
等。然后,当您应用 PIVOT 函数时,您将在单独的列中为每个所有者返回客户:
SELECT *
FROM
(
SELECT [owner], [owner_email], [customer],
'Name'+cast(row_number() over(partition by owner
order by customer) as varchar(50)) name
FROM tTableName
) AS source
PIVOT
(
MAX([customer])
FOR [name] IN ([name1],[name2],[name3],[name4],[name5])
) as pvt;
请参阅SQL Fiddle with Demo。
如果您要为每个所有者拥有超过 5 个名称,那么您可以使用动态 SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ','
+ QUOTENAME('Name'+cast(row_number() over(partition by owner
order by customer) as varchar(50)))
from tTableName
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [owner], [owner_email],' + @cols + '
from
(
SELECT [owner], [owner_email], [customer],
''Name''+cast(row_number() over(partition by owner
order by customer) as varchar(50)) name
FROM tTableName
) x
pivot
(
max(customer)
for name in (' + @cols + ')
) p '
execute(@query);
请参阅SQL Fiddle with Demo。这些会产生一个结果:
| OWNER | OWNER_EMAIL | NAME1 | NAME2 | NAME3 | NAME4 | NAME5 |
-----------------------------------------------------------------------------
| dude1 | email1 | customer1 | customer2 | customer3 | (null) | (null) |
| dude2 | email2 | customer4 | customer5 | (null) | (null) | (null) |