现有如下三张表:
已知A表的编号,需要查询表C中高和矮分别的总共年龄的总和,请问可以如何写出这个SQL语句,我试了好多次,水平有限, 没法写出来,不胜感激。
我的思路是:
1,先根据表A查出编号
2,根据每一个表A的编号,查询出表B中对应的号码(有可能是一对多)
3,根据表B中查询出的每一组的号码,然后分别进行统计表C中对应的高、矮两个条件的年龄的总和。
但是语句写不出来。
现有如下三张表:
已知A表的编号,需要查询表C中高和矮分别的总共年龄的总和,请问可以如何写出这个SQL语句,我试了好多次,水平有限, 没法写出来,不胜感激。
我的思路是:
1,先根据表A查出编号
2,根据每一个表A的编号,查询出表B中对应的号码(有可能是一对多)
3,根据表B中查询出的每一组的号码,然后分别进行统计表C中对应的高、矮两个条件的年龄的总和。
但是语句写不出来。
为了示范,所在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.编号 = :编号
4 回答1.4k 阅读✓ 已解决
8 回答1.3k 阅读
2 回答1.5k 阅读✓ 已解决
3 回答1k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
2 回答866 阅读✓ 已解决
2 回答867 阅读✓ 已解决