可以使用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