动态 SQL UNPIVOT 和 Select INTO 临时 table

Dynamic SQL UNPIVOT and Select INTO temporary table

我知道有一些关于动态 SQL 和插入临时表的问题,但我找不到与我的特定问题完全匹配的问题。

我在 ##tmp 中有 52 列的数据,我需要将这些数据合计并存储在 ##tmp2 中。

注意:语法工作正常,如果我删除了第一行

 select * into ##tmp2 from

我有问题的是"Select Into"!我当前的动态查询提供了以下语法,但我无法使其正常工作。目前,初始 "from" 之后的左括号没有匹配的右括号。

我为最后的“)”尝试了各种位置,但得到了

的混合
Incorrect syntax near ')' -- if placed at the end of the statement
Invalid column name 'wk' -- if added as  "from ##tmp) onto the second from"
Incorrect syntax near the keyword 'group'. -- if added after ")) as U"

这是当前语法

select * into ##tmp2 from(
select x,y,sum(wk) as mysum  from ##tmp
  unpivot (wk for nwk in ([1],[2],[3],[4],[7],[8],[9],[10],[11],[12],[13],   [14],[15],[16],
[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],
[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52]))
 as u  group by x,y

有什么想法吗?

使用:

select x,y,sum(wk) as mysum 
into ##tmp2 
from ##tmp 
unpivot (wk for nwk in ([1],[2],[3],[4],[7],[8],[9],[10],[11],[12],[13], [14],[15],[16], [17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],‌​[33],[34], [35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],‌​[51],[52])) as u 
group by x,y