sql server分组查询前几条数据的问题。

鲜米 2008-10-27 10:28:02
各位大哥,麻烦帮帮忙,求急救!求急救!
userid asuserid productid updatetime
-------------------------------------------------------
test1021 51 1310738 2008-10-23 09:56:21.013
test1021 51 1310740 2008-10-23 09:55:56.293
fanily001 51 1310735 2008-10-23 09:38:57.123
fanily001 51 1310739 2008-10-23 09:36:23.000
fanily001 51 1310736 2008-10-23 09:35:21.000
fanily001 51 1310737 2008-10-23 09:33:28.000
shaogen000 51 1310734 2008-10-22 18:03:54.000
shaogen000 51 1310733 2008-10-22 18:03:34.000
shaogen000 51 1310732 2008-10-22 18:00:06.000
shaogen000 51 1310731 2008-10-22 17:59:49.000
shaogen001 51 1310729 2008-10-22 17:55:42.000
shaogen001 51 1310730 2008-10-22 17:50:57.000
shaogen001 51 1310728 2008-10-22 17:17:22.000
shaogen001 51 1310727 2008-10-22 17:16:46.000
shaogen001 51 1310726 2008-10-22 17:05:22.000
shaogen001 51 1310725 2008-10-22 17:02:47.000
testofwk1021 51 1310724 2008-10-21 19:32:29.000
ofweek1020 51 1310723 2008-10-21 18:57:43.000
ofweek109 51 1310722 2008-10-21 18:53:35.000
register 51 1310721 2008-10-21 17:47:23.000
register 51 1310720 2008-10-21 17:44:25.000
register 51 1310719 2008-10-21 17:39:40.000
register 51 1310718 2008-10-21 17:36:07.000
testofweek16 51 1310717 2008-10-21 17:35:54.000
20081016 51 1310716 2008-10-20 17:53:26.000
blog10009 51 1310715 2008-10-20 14:34:36.000
testofweek16 51 1310714 2008-10-17 09:35:14.043
testofweek16 51 1310713 2008-10-17 09:34:53.920
testofweek16 51 1310712 2008-10-17 09:34:19.670

在上面的数据中,我要按userid字段查出每个userid用户的前三条数据。这个sql语句怎么写?
...全文
612 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
jsp_forward 2011-04-20
  • 打赏
  • 举报
回复
分组查询里面用了top也不行查出来的数据还是所有的数据结果这个我试过的。
fcuandy 2008-10-27
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20080123/18/9731d130-0d4b-4c11-8d89-f2c3ca331f0c.html
鲜米 2008-10-27
  • 打赏
  • 举报
回复
3楼的大哥,因为updatetime在列表字段中没有出现,会报如下错误:
'Updatetime' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。
这里怎么解决?
wujumao 2008-10-27
  • 打赏
  • 举报
回复
sorry,2楼的userid应该改为productid
select col1...from tb where productid=(select top 3 productid from tb group by userid,productid order by updatetime desc)
wujumao 2008-10-27
  • 打赏
  • 举报
回复
select col1...from tb where userid=(select top 3 userid from tb group by userid order by updatetime desc)

pt1314917 2008-10-27
  • 打赏
  • 举报
回复

select * from 表名 a where productid in(select top 3 productid from 表名 where userid=a.userid)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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