您可以将 aPIVOT
用于此结果。如果您知道列数,则可以对它们进行硬编码:
select *
from
(
select p.productid,
p.productname,
i.imagefilename,
'ImageFile_' +
cast(row_number() over(partition by i.productid
order by i.productid) as varchar(10)) col
from tblproducts p
left join tblProductImages i
on p.productid = i.productid
) x
pivot
(
max(imagefilename)
for col in ([ImageFile_1], [ImageFile_2], [ImageFile_3])
) p
请参阅带有演示的 SQL Fiddle
或者您可以使用动态 SQL 生成PIVOT
. 如果您的数量不断变化,动态将起作用imagefilename
:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ','
+ QUOTENAME('ImageFile_'+ cast(x.rn as varchar(10)))
from
(
select row_number() over(partition by i.productid
order by i.productid) rn
from tblProductImages i
) x
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT productid, productname,' + @cols + '
from
(
select p.productid,
p.productname,
i.imagefilename,
''ImageFile_'' +
cast(row_number() over(partition by i.productid
order by i.productid) as varchar(10)) col
from tblproducts p
left join tblProductImages i
on p.productid = i.productid
) x
pivot
(
max(imagefilename)
for col in (' + @cols + ')
) p '
execute(@query)
请参阅带有演示的 SQL Fiddle
这两个结果都将与此类似:
PRODUCTID | PRODUCTNAME | IMAGEFILE_1 | IMAGEFILE_2 | IMAGEFILE_3
==================================================================
1 | Product 1 | Image1 | Image2 | Image3
2 | Product 2 | Image1 | Image2 | (null)
3 | Product 3 | Image1 | (null) | (null)
4 | Product 4 | Image1 | Image2 | Image3
5 | Product 5 | Image1 | (null) | (null)