求一难度较高的SQL语句

pcvc 2007-06-17 11:11:56
现在有表T1:
GroupID Hits UserID
4 954 20
3 678 20
2 500 21
4 100 23
2 49 20
1 25 20

要求:取每一个用户点击数最多的GroupID,每一用户只取一个,前一个用户取过的GroupID后面的不取.如此表中:用户ID为20的取GroupID为4,用户ID为21的取GroupID为2,用户ID为23的不取,因为用户ID为23对应的GroupID为4在前面用户ID为20的取过了!

高手们,这能不能用SQL语句来实例啊???? 拜托了, 谢谢!
...全文
146 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
pcvc 2007-06-17
  • 打赏
  • 举报
回复
你们的热情感动了我, 高手!!, 谢谢你们.
结帖!!!!!!!
simonhehe 2007-06-17
  • 打赏
  • 举报
回复
declare @t table(GroupID int,Hits int,UserID int)
insert into @t
select 4,954,20 union all
select 3,678,20 union all
select 2,500,21 union all
select 4,100,23 union all
select 2,49,20 union all
select 1,25,20


select GroupID,Hits = max(Hits)
from @t
where Hits in (select Hits = max(Hits) from @t group by UserID)
group by GroupID
order by GroupID desc
hellowork 2007-06-17
  • 打赏
  • 举报
回复
declare @t table(GroupID int, Hits int, UserID int)
insert @t
select 4, 954, 20 union all
select 3, 678, 20 union all
select 2, 500, 21 union all
select 4, 100, 23 union all
select 2, 49, 20 union all
select 1, 25, 20

----方法1:
select distinct(GroupID) from @t as a where not exists(select 1 from @t where UserID = a.UserID and Hits > a.Hits)
----方法2:
select distinct(GroupID) from @t as a where Hits = (select max(Hits) from @t where UserID = a.UserID)


/*结果
GroupID
-----------
2
4
*/
bill024 2007-06-17
  • 打赏
  • 举报
回复
set nocount on
create table test(GroupID int,Hits int,UserID int)
insert test select 4,954,20
union all select 3,678,20
union all select 2,500,21
union all select 4,100,23
union all select 2,49,20
union all select 1,25,20

select * into # from
(
select * from test a where not exists
(
select 1 from test where UserID=a.UserID and Hits>a.Hits
)
)a

select GroupID from # a where UserID=
(
select top 1 UserID from # where GroupID=a.GroupID
)

drop table test,#

--result
GroupID
-----------
4
2
pcvc 2007-06-17
  • 打赏
  • 举报
回复
就拿这表:
GroupID Hits UserID
4 954 20
3 678 20
2 500 21
4 100 23
2 49 20
1 25 20

取出来的GroupID应为:
GroupID
4
2


用户23对应的GroupID-4在用户20已取过.

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧