我有一个表格中的条目列表,我试图在数据透视表查询中使用,如下所示。
SELECT *
FROM
(
SELECT [week_end], [identify_entity], [count_num]
FROM weekly_counts_t
) AS source
PIVOT
(
MAX([count_num])
FOR [identify_entity] IN ([a], [b] ...and so on)
) as pvt
下面的'for in'
查询尝试使用来自其他表的select查询中的列表
FOR [identify_entity] IN (select identify_entity from temp_table)
代替
FOR [identify_entity] IN ([a], [b] ...and so on)
这是一个键入条目的手动过程。
所以现在,我需要将列表作为方括号中的条目并用逗号分隔。有人可以帮帮我吗?谢谢!
答案 0 :(得分:0)
试试这个..
DECLARE @identify_entity NVARCHAR(MAX);
SET @identify_entity = '';
SELECT @identify_entity = @identify_entity + ',[' + [identify_entity] + ']'
FROM (SELECT DISTINCT [identify_entity] FROM weekly_counts_t) t
SET @identify_entity = STUFF(@identify_entity, 1, 1,'')
DECLARE @Sql NVARCHAR(MAX);
SET @Sql = 'SELECT *
FROM
(
SELECT [week_end], [identify_entity], [count_num]
FROM weekly_counts_t
) AS source
PIVOT
(
MAX([count_num])
FOR [identify_entity]
IN ('+ @identify_entity +')
) as pvt'
EXECUTE sp_executesql @Sql