关于 分组每次取随机 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有其他更好的方法,望一起讨论。
09-26
09-26
09-26