嵌套插入SQL查询

时间:2014-02-24 12:25:11

标签: sql sql-server nested

我使用MS sql作为数据库。我想为此编写一个嵌套查询。我的疑问是:

INSERT INTO [Node-churn](total_amount_in)  values=
       (SELECT sum(cast(amount as float)) 
        FROM [CDR-IN] 
        WHERE [Node-churn].subscriber=[CDR-IN].callee) 
WHERE degree <6

运行此查询时出错。这个问题的正确查询是什么?

P.S:Node-churn=(subscribers,degree)CDR-IN=(caller,callee,amount)

2 个答案:

答案 0 :(得分:1)

这就是select陈述的内容:

insert into [Node-churn](total_amount_in)
    select sum(cast(amount as float))
    from [CDR-IN]
    where [Node-churn].subscriber = [CDR-IN].callee and degree < 6;

但我认为你想要一个update

update [Node-churn]
    set total_amount_in = (select sum(cast(amount as float))
                           from [CRD-IN]
                           where [Node-churn].subscriber = [CDR-IN].callee
                          )
    where degree < 6;

答案 1 :(得分:0)

我不确定您是否可以在插入查询中使用WHERE。也许这是一个错字,正确的语法是

INSERT INTO [Node-churn](total_amount_in)  values= 
   (SELECT sum(cast(amount as float)) 
    FROM [CDR-IN] 
    WHERE [Node-churn].subscriber=[CDR-IN].callee and degree <6
)