2012-10-13 27 views
0

我有一个表像mytrade以下如何在sql查询中使用派生表列?

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 

现在我想要插入到第二表中的数据,基于“总”数量。

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

,但得到的错误:

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

如果我把这整个语句放入#temptable,然后如上分配然后也得到这个错误我该如何绑定“总计”列请引导我?

+1

你在哪里引用from子句中的#tempTable? –

回答

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一个完整的工作方案。

0
select securityid,quantity,101.1 from #temptable 
where #temptable.total = 13000 and securityid = 899