两个表 A,B
表A有两个列
a_name  a_num 
aa     1   
bb     3   
cc     3   
bb     2    
aa     1    
aa     6    
bb     1   
cc     2    
aa     2    
求取得相同的a_name中a_num的和
a_name的值不固定,a_num为数字输出如下:
a_name   a_num
aa     10    /* 1+1+6+2 */
bb     4     /* 3+2+1 */
cc     5     /* 3+2 */然后把求和后的 a_num值 赋予 表B b_num ,其中表A的列a_name与b_name相同
name   b_num
aa     10    /* 1+1+6+2 */
bb     4     /* 3+2+1 */
cc     5     /* 3+2 */请问这个语句要怎么写。

解决方案 »

  1.   

    第一步,我找到答案了,
    select a_name , sum(a_num) from A group by a_name
    但是第二步,要 使 表B b_num=a_num 就不知道怎么写了!
      

  2.   


    update b
    set b_num=t.s
    from (select a_name, sum(a_num) s from A group by a_name) t
    where t.a_name=b.name
      

  3.   

    我比较喜欢这样写:UPDATE B
    SET b.b_num=t.s
    FROM B as B inner join (SELECT a_name,sum(a_num) s FROM A GROUP BY a_name) as t
    因为上面的写法对我来说,可读性不强。当然能解决问题。另外,SQLServer2008中有一个merge关键字可以实现一次性更新。详细请看联机丛书。
      

  4.   

    我把两个表套进去发现,有提示错误,能帮我修改一下吗? 
    update t_da_jxc_daysum
        set pos_amt=t.s
        from (select item_no, sum(sale_amt) s from t_rm_daysum where oper_date='2012-06-01' item_no) t
        where t.item_no=t_rm_daysum.item_no and t_da_jxc_daysum.oper_date='2012-06-01' and t_rm_daysum.oper_date='2012-06-01'
    服务器: 消息 107,级别 16,状态 3,行 1
    列前缀 't_rm_daysum' 与查询中所用的表名或别名不匹配。
    服务器: 消息 107,级别 16,状态 1,行 1
    列前缀 't_rm_daysum' 与查询中所用的表名或别名不匹配。
      

  5.   

    第二种方式 
    UPDATE t_da_jxc_daysum
    SET t_da_jxc_daysum.pos_amt=t.s
    FROM t_da_jxc_daysum as t_da_jxc_daysum inner join (SELECT pos_amt,sum(sale_amt) s FROM t_rm_daysum GROUP BY sale_amt) as t服务器: 消息 170,级别 15,状态 1,行 3
    第 3 行: 't' 附近有语法错误。
      

  6.   


    既然第一步你明白了,上面DBA的写法也很好,不过建议你分步理解吧select a_name as temp_name , sum(a_num)as temp_num into #temp from A group by a_name --把查询结果存到临时表#temp中select *  from  #temp  --验证是否有数据update B  set B.b_num=#temp.temp_num  where B.b_name=#temp.temp_name 更新B表这个是化简为繁,不过如果你表比较多的话这样你好理解
      

  7.   


    with temp  as
    (
    select a_name as name,
           sum(a_num) as  num
    from  A
    froup by a_name
    )update
    B
    set b_num=
    (select num from temp where b_name=name)