请教SQL统计多个表的问题

qzw4549689 2014-02-14 11:15:19
假设有三张表:user,dataA,dataB
假设数据如下:
user表:
id name
1 张三
2 李四

dataA表:
userid contentA
1 XXX
2 XXX

dataB 表:
userid contentB
1 XXX
1 XXX
2 XXX

最终想要的结果是这样:
userid dataAnum dataBnum
张三 1 2
李四 1 1



...全文
52 点赞 收藏 2
写回复
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2014-02-14

create table users
(id int,name varchar(10))

insert into users
 select 1,'张三' union all
 select 2,'李四'

create table dataA
(userid int,contentA varchar(10))

insert into dataA
 select 1,'XXX' union all
 select 2,'XXX'

create table dataB
(userid int,contentB varchar(10))

insert into dataB
 select 1,'XXX' union all
 select 1,'XXX' union all
 select 2,'XXX'


select a.name 'userid',
       isnull(b.qty,0) 'dataAnum',
       isnull(c.qty,0) 'dataBnum'
 from users a
 left join
 (select userid,count(1) 'qty' 
  from dataA 
  group by userid) b on a.id=b.userid
 left join
 (select userid,count(1) 'qty' 
  from dataB 
  group by userid) c on a.id=c.userid

/*
userid     dataAnum    dataBnum
---------- ----------- -----------
张三         1           2
李四         1           1

(2 row(s) affected)
*/
回复
是这样吗:
create table [user](id int,name varchar(10))

insert into [user]
select 1   ,'张三' union all
select 2   ,'李四'

create table  dataA(userid int,contentA varchar(10))

insert into dataA
select 1      ,'XXX' union all
select 2       ,'XXX'

create table dataB(userid int, contentB varchar(10))

insert into dataB
select 1       ,'XXX' union all
select 1       ,'XXX' union all
select 2       ,'XXX'
go

select --id,
       name,
       (select COUNT(*) from dataA where userid = t.id) as dataAnum,
       (select COUNT(*) from dataB where userid = t.id) as dataBnum
from [user] t
/*
name	dataAnum	dataBnum
张三	1	2
李四	1	1
*/
回复
发动态
发帖子
疑难问题
创建于2007-09-28

2.1w+

社区成员

MS-SQL Server 疑难问题
申请成为版主
社区公告
暂无公告