0
select @cols =
STUFF((SELECT ',' + QUOTENAME(grade)
from #temp
group by grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsRollup = STUFF((SELECT ', Sum(' + QUOTENAME(grade) + ') as '+QUOTENAME (grade)
from #temp
group by grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT * into #temp3 from
(
SELECT lob as "Vertical", '+ @colsRollup + '
FROM
(
SELECT lob,' + @cols + ' from
(
select lob,
grade,
asso_count
from #temp
) x
pivot
(
count(grade)
for grade in (' + @cols + ')
) p
) x1
GROUP BY lob with ROLLUP)x2'
execute(@query)
我想創建動態列並將其插入臨時表。 但它會拋出一個錯誤,指出#temp3不是有效的對象名稱。如果我不嘗試將動態生成的列插入到表中,代碼將起作用。SQL動態列
mysql或sql-server?選擇一個並編輯標籤。 (它看起來像SQL服務器) – slavoo
嗨,其SQL Server。 –
@prasanthunnikrishnan你怎麼執行這個?在存儲過程或其他方式? – jpw