我有3张表
U表     userid,username
        1      a
        2      b
        3      c
        4      d
A表     userid,amount,date
         1      10
        2      11
        1      12
        3      34
B表     userid,amount,date
        1      20
        2      40
        2      33请问我如何构造查询语句,得出A表+B表各个userid的amount总和
        即
         1      42
        2      84
        3      34

解决方案 »

  1.   

    select userid,sum(amount) 
    from (select userid,amount from a union select userid,amount from b);
      

  2.   

    select userid.sum(amount) from (
       select userid,amount from a
       union
       select userid,amount from b) AB
    group by userid
      

  3.   


    select userid.sum(amount) from ( 
      select userid,amount from a 
      union all
      select userid,amount from b) AB 
    group by userid
      

  4.   


    --> 测试数据: @A表
    declare @A表 table (userid int,amount int)
    insert into @A表
    select 1,10 union all
    select 2,11 union all
    select 1,12 union all
    select 3,34--> 测试数据: @B表
    declare @B表 table (userid int,amount int)
    insert into @B表
    select 1,20 union all
    select 2,40 union all
    select 2,33select aa.userid ,sum(amount) as [sum] from 
    ( select * from @A表 union all
      select * from @B表
    ) aa 
    group by userid
    /*
    userid      sum
    ----------- -----------
    1           42
    2           84
    3           34
    */