两张表A,BA表如下:id       cname        a
-------------------------
1        数据库       20
1        SQL          30B表如下:id        pname        b
--------------------------
1         编程         50
如何查询:当A,B两张表id=1时,对a,b字段求和的结果也就是结果要这样:id                     a+b
----------------------------
1                      100
请前辈们赐教!

解决方案 »

  1.   

    SELECT A.ID,SUM(A.A)+SUM(B.B)
    FROM A,B
    WHERE A.ID=B.ID AND A.ID=1
    GROUP BY A.ID
      

  2.   

    select id,sum(b)
    from (select id,b from tb where id = 1 
          union all
          select id,a from ta where id = 1)
    group by id
      

  3.   

    select id,sum(b)
    from (select id,b from tb where id = 1 
    union all
    select id,a from ta where id = 1) a
    group by id
      

  4.   

    SELECT A.ID,A+B FROM 
    (
    SELECT A.ID,SUM(A) A FROM A GROUP BY A.ID
    )A
    ,
    (
    SELECT B.ID,SUM(B) B FROM B GROUP BY B.ID
    )B 
    WHERE A.ID=B.ID
      

  5.   

    select id , sum(val) val from
    (
    select id , val = a from a where id = 1
    union all
    select id , val = b from b where id = 1
    ) t
    group by id
      

  6.   

    create table A(id int,cname varchar(10),a int)
    insert into a values(1 ,'数据库', 20)
    insert into a values(1 ,'SQL' ,30)
    create table b(id int,pname varchar(10),b int)
    insert into b values(1 ,'编程', 50)select id , sum(val) val from
    (
    select id , val = a from a where id = 1
    union all
    select id , val = b from b where id = 1
    ) t
    group by iddrop table a , b/*id          val         
    ----------- ----------- 
    1           100(所影响的行数为 1 行)
    */