【问题标题】:Dynamic SQL UNPIVOT and Select INTO temporary table动态 SQL UNPIVOT 和 Select INTO 临时表
【发布时间】:2016-01-22 19:36:54
【问题描述】:

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

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

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

 select * into ##tmp2 from

这是我有问题的“选择进入”!我当前的动态查询提供以下语法,但我无法让它工作。目前,初始“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
  • 谢谢@lad2025。杰出的!它有效!

标签: sql-server tsql sql-server-2005 dynamic-sql


【解决方案1】:

用途:

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

【讨论】:

  • 它确实有效!我发誓确实如此。但是,将语句放入动态查询后,我现在在使用上述语法时收到语法错误Incorrect syntax near the keyword 'as'.(在unpivot 行上)。我要疯了吗??我的语法和上面一模一样!
  • @MiguelH 可能缺少括号见更新[52])) as u
  • 太棒了!丢失的支架解决了它!我应该自己发现的!
  • @MiguelH 这种错别字是最糟糕的,尤其是当您盯着文字墙数小时时。我知道那种痛苦:)
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 2011-02-24
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 2018-05-22
相关资源
最近更新 更多