【发布时间】:2016-12-02 14:11:01
【问题描述】:
我正在尝试实现动态 sql 数据透视,其中两个表连接在一起,一组图像成为它们自己的列。
表 1:
house_id name value
1 image image1.jpg
1 image image2.jpg
1 image image3.jpg
表 2:
id updated_at house_name
1 2016-12-02 House 1
我希望它看起来像这样:
house_id updated_at house_name image1 image2 image3
1 2016-12-02 House 1 image1.jpg image2.jpg image3.jpg
我想通过动态 sql 数据透视来实现这一点,但我无法让它工作(即使没有连接):
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(name) + ',' FROM (select distinct name from #table1 ) as house_meta
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end
set @query =
'SELECT * from
(
select house_id, name, value from #table1
) src
pivot
(
max(value) for name in (' + @cols + ')
) piv'
execute(@query)
【问题讨论】: