【问题标题】:How to use use derived table column in sql query?如何在sql查询中使用派生表列?
【发布时间】:2012-10-13 17:52:02
【问题描述】:

我有一张 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”列,请指导我?

【问题讨论】:

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

标签: sql sql-server sql-server-2008 tsql


【解决方案1】:

试试这个:

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 上找到完整的工作解决方案。

【讨论】:

    【解决方案2】:
    select securityid,quantity,101.1 from #temptable
    where #temptable.total = 13000 and securityid = 899
    

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2017-03-29
      • 2019-06-29
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多