高手帮忙写一条sql语句!
表AA
id shop_id user_id shu
1 11 111 10
2 22 333 20
3 33 222 30
4 33 111 50
5 33 333 50
6 33 222 50
7 33 444 50
8 33 111 50
表BB
id aa bb cc bb ee
111 ………………………………
222 ………………………………
333 ………………………………
结果:
查询出AA表中user_id 次数最多的前3条记录
如 user_Id
111
222
333
数据
并关联到BB表中查出他的所有信息!!再统计出 每个user_Id 的总(shu)
如 user_Id shu
111 110
222 80
------解决方案--------------------select 表BB.*,t.[user_id],t.shu
from (select top 3 [user_id],sum(shu) as shu
from 表AA
group by [user_id]
order by count(*) desc)t,表BB
where t.[user_id]=表BB.id
------解决方案--------------------Select
A.*,
B.aa
From
(
Select
TOP 3
[user_Id],
SUM(shu) As shu
From
AA
Group By [user_Id]
Order By Count(*) Desc
) A
Inner Join
BB B
On A.[user_Id] = B.[id]
------解决方案--------------------:)
差不多的
------解决方案--------------------if object_id( 'pubs..tb ') is not null
drop table tb
go
create table tb(id int,shop_id int,[user_id] int,shu int)
insert into tb(id,shop_id,[user_id],shu) values(1, 11, 111, 10)
insert into tb(id,shop_id,[user_id],shu) values(2, 22, 333, 20)
insert into tb(id,shop_id,[user_id],shu) values(3, 33, 222, 30 )
insert into tb(id,shop_id,[user_id],shu) values(4, 33, 111, 50)
insert into tb(id,shop_id,[user_id],shu) values(5, 33, 333, 50)
insert into tb(id,shop_id,[user_id],shu) values(6, 33, 222, 50)
insert into tb(id,shop_id,[user_id],shu) values(7, 33, 444, 50)
insert into tb(id,shop_id,[user_id],shu) values(8, 33, 111, 50)