可以使用PIVOT
这一结果。如果您知道列的数量,那么你可以硬编码它们:
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 with Demo
或者您可以使用动态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 with Demo
两个结果将类似于此:
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)
你真的想拥有动态数你的结果中的列? –
如果imagefile不存在,那么你的结果中是否有10列固定并保留为空值? – AnandPhadke
我强烈建议或者保留规范化集合(有两个查询)或一个集合(如你所愿),但有固定数量的fileName字段。 – MatBailie