select a.id,a.CustomID,a.Name,sales=sum(b.sales)
from A join B on a.CustomID=b.CustomID
group by a.id,a.CustomID,a.Name

解决方案 »

  1.   

    --所有客户应该用left joinselect a.id,a.CustomID,a.Name,sales=sum(b.sales)
    from A left join B on a.CustomID=b.CustomID
    group by a.id,a.CustomID,a.Name
      

  2.   

    --测试--测试数据
    create table A(ID int,CustomID int,Name varchar(10))
    insert A  select 1,1001,'张三'
    union all select 2,1002,'李四'
    union all select 3,1003,'王五'create table B(ID int,CustomID int,sales decimal(10,2))
    insert B  select 1,1002,59.00
    union all select 2,1001,77.00
    union all select 3,1002,65.00
    union all select 4,1002,88.00
    go--查询统计
    select a.id,a.CustomID,a.Name,sales=sum(b.sales)
    from A left join B on a.CustomID=b.CustomID
    group by a.id,a.CustomID,a.Name
    go--删除测试
    drop table a,b/*--测试结果
    id          CustomID    Name       sales        
    ----------- ----------- ---------- -------------
    1           1001        张三         77.00
    2           1002        李四         212.00
    3           1003        王五         NULL(所影响的行数为 3 行)--*/
      

  3.   

    --去掉NULL值的处理:select a.id,a.CustomID,a.Name,sales=sum(isnull(b.sales,0))
    from A left join B on a.CustomID=b.CustomID
    group by a.id,a.CustomID,a.Name
      

  4.   

    select A.* sum(B.sales)
    from A B
    where A.customID=B.customID可不可以这样啊?
      

  5.   

    --上面的不行,要改为:select A.* sum(B.sales)
    from A ,B  --加逗号
    where A.customID=B.customID
    group by group by a.id,a.CustomID,a.Name  --加group by 
      

  6.   

    to: zjcxc(邹建)
    本来我得A表有很多字段,是不是group by 语句要包含所有的字段?
      

  7.   

    对,group by 语句要包含除了聚合字段以外所有的字段。