试试这个:
create table jt(家庭ID int, 姓名 varchar(10),序号 int)insert into jt
select 1   ,'张三',   1 union  all
select 1   ,'李四',   2 union  all
select 1   ,'王五',   3 union  all
select 2   ,'小a',   1 union  all
select 2   ,'小b',   2create table xjl(家庭ID int,  序号  int,  消费金额 int)insert into xjl
select 1 ,     1,       100 union all
select 1 ,     3,        45
go
select jt.家庭ID,
       COUNT(*) as 人数,
       isnull(SUM(xjl.消费金额),0) as 合计消费
from jt
left join xjl
       on jt.家庭ID = xjl.家庭ID
          and jt.序号 = xjl.序号
group by jt.家庭ID
/*
家庭ID 人数 合计消费
1 3 145
2 2 0
*/

解决方案 »

  1.   


    create table jt
    (家庭ID int,姓名 varchar(10),序号 int)insert into jt
     select 1,'张三',1 union all
     select 1,'李四',2 union all
     select 1,'王五',3 union all
     select 2,'小a',1 union all
     select 2,'小b',2create table xjl
    (家庭ID int,序号 int,消费金额 int)insert into xjl
     select 1,1,100 union all
     select 1,3,45
    select a.家庭ID,a.人数,isnull(b.合计消费,0) '合计消费'
    from 
    (select 家庭ID,
            count(1) '人数'
     from jt group by 家庭ID) a
    left join 
    (select 家庭ID,sum(消费金额) '合计消费'
      from xjl group by 家庭ID having sum(消费金额)>20) b on a.家庭ID=b.家庭ID/*
    家庭ID        人数          合计消费
    ----------- ----------- -----------
    1           3           145
    2           2           0(2 row(s) affected)
    */