我正在为新报告提出一个基本查询,并且遇到了这个小问题。
我有两个表Buildings
(B)和Pictures
(P),两者中的键是BuildingNumber。我在两个表之间有一个简单的内连接。我遇到的问题是我有B栋的183栋建筑物,但每栋建筑物都有多张图片,每栋建筑物的图片数量并不一致。因此,当我得到结果集时,它返回大约260行。我想要做的是为每个建筑物返回一行,并为与该建筑物相关联的每个图片添加一列。请记住,我无权更改或创建表格。
我的数据是这样的:
建筑表(B):
BuildingNumber BldgName Floors SqFt
0001 Science 5 50000
0002 Engineering 4 40000
图片表(P):
BuildingNumber PictureURL
0001 URL1
0001 URL2
0001 URL3
0002 URL1
0002 URL2
所以我想要的结果设置如下:
BuildingNumber BldgName Floors SqFt PictureURL1 PictureURL2 PictureURL3
0001 Science 5 50000 URL1 URL2 URL3
0002 Engineering 4 40000 URL1 URL2 NULL
答案 0 :(得分:4)
您可以使用PIVOT函数获取结果,此函数会将您的数据行转换为列。
如果每个建筑物的PictureURLs
数量有限,那么您可以对查询进行硬编码:
select BuildingNumber, bldgname, floors, sqft,
PictureURL1, PictureURL2, PictureURL3
from
(
select b.BuildingNumber, b.bldgname, b.floors, b.sqft,
p.PictureURL,
col = 'PictureURL'+
cast(row_number() over(partition by b.BuildingNumber
order by b.BuildingNumber) as varchar(10))
from building b
inner join picture p
on b.BuildingNumber = p.BuildingNumber
) d
pivot
(
max(PictureURL)
for col in (PictureURL1, PictureURL2, PictureURL3)
) piv;
见SQL Fiddle with Demo。但是如果你有一个未知数量的值,那么你将不得不考虑使用动态SQL。这将创建一个sql字符串,将执行该字符串以获得最终结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('PictureURL'+
cast(row_number() over(partition by BuildingNumber
order by BuildingNumber) as varchar(10)))
from Picture
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT BuildingNumber, bldgname, floors, sqft,' + @cols + '
from
(
select b.BuildingNumber, b.bldgname, b.floors, b.sqft,
p.PictureURL,
col = ''PictureURL''+
cast(row_number() over(partition by b.BuildingNumber
order by b.BuildingNumber) as varchar(10))
from building b
inner join picture p
on b.BuildingNumber = p.BuildingNumber
) x
pivot
(
max(PictureURL)
for col in (' + @cols + ')
) p '
execute sp_executesql @query;
见SQL Fiddle with Demo。两者都给出了结果:
| BUILDINGNUMBER | BLDGNAME | FLOORS | SQFT | PICTUREURL1 | PICTUREURL2 | PICTUREURL3 |
| 1 | Science | 5 | 50000 | URL1 | URL2 | URL3 |
| 2 | Engineering | 4 | 40000 | URL1 | URL2 | (null) |