2014-05-21 51 views
0

我有一張試圖在透視表查詢中使用的表的列表,如下所示。方括號包圍了來自select語句的逗號分隔列表

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'查詢想從其它表 FOR [identify_entity] IN (select identify_entity from temp_table)代替 FOR [identify_entity] IN ([a], [b] ...and so on)這是項鍵控的手動過程中使用列表從選擇查詢。

所以現在,我需要列表作爲方括號中的條目,並用逗號分隔。有人請幫助我嗎?謝謝!

+0

你讀過這個問題? http://stackoverflow.com/questions/2283674/pivot-sql-values-from-subquery/2283909#2283909。這些答案中的一些看起來與您正在嘗試完成的內容類似。 – AHiggins

回答

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 
相關問題