试试这个:
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
*/
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
*/
解决方案 »
- 怎样删除数据中的邮政编码?
- .mdf和.ldf打开方式是什么?
- sql server sum()
- 最近数据库老是死锁,系统老是写不进数据,或者很多用户,只有某部分用户才能输入,正在想,是不是程序中用了一些语句把某些表给锁死了呢?
- 请问,sqlserver 2005 sqlexpress版有没有用户数限制呢?
- 求一存储过程写法,上了好多论坛都没有结果,郁闷阿,各位高人请来这里赐教
- 在sql企业管理器中建立person数据库时出错,望提示
- 求助,SQL视图运行正常,保存时报错
- 在sql server 6.5数据库中,如何清空日志?
- 规整的word文档,怎么将其按字段导入数据库中?
- 求UPDATE触发器语句
- 这两种种数据库连接方式各有什么优缺点?
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)
*/