动态sql枢轴连接

时间:2016-12-02 14:11:01

标签: sql dynamic pivot

我正在尝试实现一个动态的sql pivot,其中两个表连接在一起,一组图像成为它们自己的列。

表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 pivot来实现这一点,但我无法让它工作(即使没有连接):

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)

1 个答案:

答案 0 :(得分:0)

无法使用{ "name": "asp.net", "private": true, "dependencies": { "jquery-validation": "~1.15.1", "knockoutjs": "~3.4.1", "knockout.mapping": "~2.0.1", "knockout-validation": "~2.0.3", "bootstrap": "~3.3.7", "jquery-validation-unobtrusive": "~3.2.6", "modernizr": "~3.3.1", "respond": "~1.4.2", "jquery": "2.2.3" }, "resolutions": { "knockout": ">=2.3.0" } } 数据类型的聚合运算符,因此您无法在此使用image