关于 分组每次取随机 top 记录

 关于 分组每次取随机 top 记录
(csdn 看见问题 心血来潮)
if object_id('tempdb..#','U')is not null drop table #
go
create table #(chapterid int, chapter varchar(10))
insert # select   1   ,           'a'
insert # select    1 ,             'b'
insert # select    1 ,             'c'
insert # select    2 ,             'd'
insert # select    2 ,             'e'
insert # select    3 ,             'f'
insert # select    1 ,             'g'
insert # select    2 ,             'h'
insert # select    2 ,             'i'
insert # select    1,              'g'

--徐王锦 2009/01/15 pm 18:17--
--
2005
select chapterid,chapter
from
(
select *,px=row_number()over(partition by chapterid order by newid())
from #)x
where px<=3
--1
/*

chapterid   chapter
----------- ----------
1           g
1           g
1           c
2           d
2           i
2           h
3           f

(7 行受影响)
*/
--2
/*

chapterid   chapter
----------- ----------
1           g
1           g
1           a
2           h
2           e
2           d
3           f

(7 行受影响)
*/
--3
/*

chapterid   chapter
----------- ----------
1           c
1           g
1           a
2           e
2           h
2           i
3           f

(7 行受影响)
*/

--2000需要中间表
--


需要一中间表
每次session 前 清空中间表
把记录存放在中间表里
把newid()从
uniqueidentifier 转换成 varbinary 
再把varbinary 转换成
int
在分组求top前几条记录
--缺点 开销大,不实用每次查询io的读写比较多
--
优点 想不出来有什么优点

--2000有其他更好的方法,望一起讨论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值