关于三表联查一对多的统计问题?

现有如下三张表:
图片描述

已知A表的编号,需要查询表C中高和矮分别的总共年龄的总和,请问可以如何写出这个SQL语句,我试了好多次,水平有限, 没法写出来,不胜感激。
我的思路是:
1,先根据表A查出编号
2,根据每一个表A的编号,查询出表B中对应的号码(有可能是一对多)
3,根据表B中查询出的每一组的号码,然后分别进行统计表C中对应的高、矮两个条件的年龄的总和。
但是语句写不出来。

阅读 5.2k
4 个回答
猜测结果1:
高和矮分别的总龄
SELECT Type, SUM(Age) Age
FROM C
GROUP BY Type

猜测结果2:
编号、高和矮分别的总龄
SELECT B.Number, C.Type, SUM(Age) Age
FROM B
LEFT JOIN C ON C.Code = B.Code
GROUP BY B.Number, C.Type

猜测结果3:
号码、高和矮分别的总龄
SELECT Code, Type, SUM(Age) Age
FROM C
GROUP BY Code, Type

猜测结果4:
编号、号码、高和矮分别的总龄
SELECT B.Number, C.Code, C.Type, SUM(Age) Age
FROM B
LEFT JOIN C ON C.Code = B.Code
GROUP BY A.Number, C.Code, C.Type

为了示范,所在C多加了几条

if object_id('tempdb..#t1') is not null drop table #t1
if object_id('tempdb..#t2') is not null drop table #t2
if object_id('tempdb..#t3') is not null drop table #t3

create table #t1 (id int);
insert into #t1(id)values(1),(2)
create table #t2(id int,code varchar(6))
insert into #t2(id,code)values(1,'1001'),(1,'1002'),(2,'1003'),(2,'1004')
create table #t3(code varchar(100),age int,type nvarchar(2))
insert into #t3
select '1001',14,N'高' union all
select '1002',13,N'矮' union all
select '1002',27,N'矮' union all
select '1003',15,N'高' union all
select '1004',17,N'高' union all
select '1005',20,N'矮' union all
select '1006',16,N'高' union all
select '1007',17,N'矮' 

select t3.code,t3.type,sum(age) as sum_age from #t1 as t1
inner join #t2 as t2 on t1.id=t2.id
inner join #t3 as t3 on t2.code=t3.code
group by t3.code,t3.type
code type sum_age
1001 14
1002 40
1003 15
1004 17


SELECT * FROM table_a
INNSER JOIN table_b ON table_a.编号=table_b.编号
INNER JOIN (SELECT 号码,sum(年龄) FROM table_c GROUP BY 号码,类型) c
ON table_b.号码=c.号码

高、矮返回两行的写法

select c.类型, sum(年龄)
from c inner join b on c.号码= b.号码
group by c.类型
where b.编号 = :编号
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题