0

我有一张 mytrade 表,如下所示

tradeid securityid quantity

111    899    12000
112    899    1000
113    788    15000
114    566    -15000
115    566    -1000

因此,为了收集安全 ID 的总量,我编写了以下查询(我在#temptable 中尝试了这个,也创建了 temptable,然后在下面选择)

select
tradeid,
securityid,
sum(quantity) OVER(Partition by securityid) as total
from mytrade

这给了我如下输出

tradeid securityid total

114    566    -16000
115    566    -16000
113    788    15000
111    899    13000
112    899    13000

现在我想根据“总”数量将值插入到 secondtable 中。

insert secondTable (securityid,quantity,price)
(
select securityid,quantity,101.1 from mydata..mytrade
where #temptable.total = 13000 and securityid = 899
)

但出现错误:

无法绑定多部分标识符“#temptable.total”。

如果我将整个语句放入#temptable,然后按上述方式分配,那么我应该如何绑定“total”列,请指导我?

4

2 回答 2

4

尝试这个:

INSERT secondTable (securityid,quantity,price)
(
SELECT securityid,quantity,101.1 FROM (
  SELECT
tradeid,
securityid,
sum(quantity) OVER(Partition BY securityid) AS total,
quantity
FROM mytrade)T
WHERE total = 13000 AND securityid = 899
)

您可以在SQL Fiddle上找到完整的工作解决方案。

于 2012-10-13T18:02:05.960 回答
0
select securityid,quantity,101.1 from #temptable
where #temptable.total = 13000 and securityid = 899
于 2012-10-13T18:01:22.993 回答