使用动态SQL将两列及其各自的值连接到表标题中

时间:2018-07-11 21:14:27

标签: sql-server dynamic-sql

我有两个表,GuestList和CustomerList。我加入了他们,并使用动态SQL数据透视表将GuestList表中的“ city”列转换为行或表标题,平均人口将显示在每个城市下。因此,在底部执行查询后,我的表格标题看起来像这样,并且在每个城市下显示了平均人口。


时间|亚特兰大|洛杉矶|纽约|丹佛|明尼阿波利斯


但是我希望我的表头看起来像这样。基本上,“ Id”具有四个值1、2、3、4,每个城市都具有这四个ID。我无法添加所有城市,但其他城市也将是这样。


时间|亚特兰大_1 ||亚特兰大_2 ||亚特兰大_3 ||亚特兰大_4 |


有人可以帮我解决这个问题,方法是编写关于如何将GuestList表中的两列连接起来并将其各自的人口放在下面的查询的其余部分。

declare @ColumnNames nvarchar(max) = ''
declare @SQL nvarchar(max) = ''

select @ColumnNames += QUOTENAME(a.address) + ','
from GuestList as a
inner join CustomerList as b
on a.Id = b.Id
group by a.address
order by a.address 

set @ColumnNames = left(@ColumnNames, LEN(@ColumnNames)-1  )

set @SQL= N'
select Time,' + @ColumnNames + '
from 
(
select a.Time, a.city, a.population, b.Gender
from GuestList as a
inner join CustomerList as b
on a.Id = b.Id
inner join Split(@city, '','') as c
on a.city = c.Data
where a.city = c.Data
) as SourceTable
pivot
(avg(population) 
for city 
in (' 
    + @ColumnNames + 
    ')) as PivotTable
order by Time'


execute sp_executesql @SQL,
                        N'@city nvarchar(max)'
                        ,@city = 'Atlanta,Los Angeles,New York'

1 个答案:

答案 0 :(得分:1)

以“ FOR XML PATH”进行救援。这是基本思想...

CREATE TABLE #ids(id NVARCHAR(20));
INSERT #ids VALUES ('1'), ('2'), ('3'), ('4');

CREATE TABLE #cities(city NVARCHAR(20));
INSERT #cities VALUES ('Atlanta'), ('Los Angeles'), ('New York'), ('Denver'), ('Minneapolis');

SELECT  'Time' + (
            SELECT  '|' + city + '_' + id
            FROM    #cities
            CROSS JOIN #ids
            ORDER BY city, id
            FOR XML PATH('')
        ) ;

...产生结果...

Time|Atlanta_1|Atlanta_2|Atlanta_3|Atlanta_4|Denver_1|Denver_2|Denver_3|Denver_4|Los Angeles_1|Los Angeles_2|Los Angeles_3|Los Angeles_4|Minneapolis_1|Minneapolis_2|Minneapolis_3|Minneapolis_4|New York_1|New York_2|New York_3|New York_4