sql server 一对多统计数量

2025-03-01 11:00:57
推荐回答(2个)
回答1:

数据

我这里叫a,b,c了,跟你表1,2,3是对应的

create table a(uid int,name varchar(10))
insert into a values (1,'张一')
insert into a values (2,'张二')


create table b (uid int,type1 varchar(1))
insert into b values (1,'a')
insert into b values (1,'b')
insert into b values (1,'c')
insert into b values (2,'b')
insert into b values (2,'c')



create table c(uid int,type2 varchar(1))
insert into c values (1,'a')
insert into c values (2,'b')
insert into c values (2,'c')

运行

select t1.uid,t2.c1,t3.c2 from a t1
left join 
(select uid,count(*) c1 from b group by uid) t2 on t1.uid=t2.uid
left join 
(select uid,count(*) c2 from c group by uid) t3 on t1.uid=t3.uid

 

结果

回答2:

--楼主这个分组就可以了
--有什么问题可以随时找我 希望采纳
select tb2.uid,count(distinct type1) type1,count(distinct type2) type2
from tb1 join tb2 on tb1.id=tb2.uid
join tb3 on tb1.id=tb3.uid
group by tb2.uid