在SQL SERVER后台有两张表,结构如下:
基础数据表A:
代码  类别  数量  生产日期
111   A     1     2009-1-2
111   B     1     2009-1-21
数据省略
B表:
代码  类别  数量
111   A     ?
111   B     ?
我想把B表中各记录在A表中相同的记录的数量个数统计出来,且要写入到B表中对应的?处.怎么写SQL 代码??

解决方案 »

  1.   

    update b
      set 数量 = isnull((select sum(数量) from a where 代码 = a.代码  and 类别 = a.类别),0)
    from a
      

  2.   

    update tb set tb.数量=a.数量 from ta where ta.代码=tb.代码 and ta.类别=tb.类别  
      

  3.   


    update B
    set
        数量=isnull((select sum(数量) from A where 代码=B.代码 and 类别=B.类别),0)
    from
        B
      

  4.   

    create table a(代码 int, 类别 varchar(10), 数量 int, 生产日期 datetime)
    insert into a values(111 , 'A' ,   1 ,   '2009-1-2' )
    insert into a values(111 , 'B' ,   1 ,   '2009-1-21') 
    create table b(代码 int, 类别 varchar(10), 数量 int)
    insert into b values(111 , 'A' , null)
    insert into b values(111 , 'B' , null)
    goupdate b
      set 数量 = isnull((select sum(数量) from a where 代码 = b.代码  and 类别 = b.类别),0)
    from bselect * from bdrop table a , b/*
    代码          类别         数量          
    ----------- ---------- ----------- 
    111         A          1
    111         B          1(所影响的行数为 2 行)*/
      

  5.   

    update tb set tb.数量=a.数量 from 
    (select 代码 , 类别,  sum(数量)数量 from ta group by 代码 , 类别 )ta where ta.代码=tb.代码 and ta.类别=tb.类别  
      

  6.   

    UPDATE B
    SET  数量=A.数量
    FROM B,(select sum(数量)数量,A.代码, A.类别
    from A,B
    where A.代码=B.代码
    and A.类别=B.类别
    group  by  A.代码, A.类别)A
    WHERE  A.代码=B.代码
    and A.类别=B.类别
      

  7.   


     update b
     Set b.數量=a.count(*)
     From   B表 b, A表 a
     where b.代碼=a.代碼 and b.類別=a.類別
     group by a.代碼,a.類別