读书人

聚合查询涉及多表时的处理方法解决方法

发布时间: 2012-01-14 20:02:35 作者: rapoo

聚合查询涉及多表时的处理方法
我有表map和record
map表记录了用户信息,列是id,comment,分别表示某人的id和姓名
例如:
id comment
1 tom
2 jerry
3 sam

record表记录了用户来访记录,列是number,id,mark,分别表示来访记录的自动编号,来访人的id和来访的内容
例如:
number id mark
1001 3 legrijo
1002 3 wogfejwg
1003 3 wgegw
1004 1 wgoeo34
1005 2 9614weg
1006 1 wgwgeg

现在要查询产生这样的结果:


id comment num
3 sam 3
1 tom 2
2 jerry 1


num表示某人的来访次数
我写的查询语句只能产生id,num这两项,再加入comment就必须用临时表,有没有办法用一个语句产生这个结果?


***********************************************************

附自己的语句:


create table #t ([id] int ,num int)

insert into #t

select id ,count(*) as num from record
group by id
order by num desc


select #t.id,m.comment,#t.num from #t,map m where m.id=#t.id
order by #t.num desc




[解决办法]
select count(aa.id) num,a.id,b.comment from record a, map b where a.id=b.id group by a.id ,b.comment

?
[解决办法]
select count(a.id) num,a.id,b.comment from record a, map b where a.id=b.id group by a.id ,b.comment order by count(aa.id) desc
[解决办法]
select a.id ,a.comment,num = (select count(*) from record where id = a.id )from map a
order by num desc
[解决办法]
Select
A.id,
A.comment,
B.num
From
map A
Inner Join (
Select id,Count(1) As Num From record Group By id) B
On A.id=B.id

读书人网 >SQL Server

热点推荐