请教sql里面如何随机选若干和为某数的若干记录
请问sql里面怎么随机选若干和为某数的若干记录
比如:
a列
1
2
3
3
4
2
6
随机选3条记录并且和为10。
该怎么写呢?谢了~!
------解决思路----------------------
比如:
a列
1
2
3
3
4
2
6
随机选3条记录并且和为10。
该怎么写呢?谢了~!
------解决思路----------------------
create table #t(a列 int,b列 varchar(20))
insert into #t
select 1,'ww' union all
select 2,'we' union all
select 3,'tryr' union all
select 3,'tyw' union all
select 4,'ewrwt' union all
select 2,'wertw' union all
select 6,'wertwertwer'
-- 测试1
declare @x int,@s int --输入参数
select @x=3, -- 每次随机选3条
@s=10 -- a列的和为10
set nocount on
declare @y int
declare @c table(a列 int,b列 varchar(20))
insert into @c(a列,b列)
select top(@x) a列,b列
from #t
order by newid()
while((select sum(a列) from @c)<>@s and isnull(@y,0)<=10000)
begin
delete from @c
insert into @c(a列,b列)
select top(@x) a列,b列
from #t
order by newid()
select @y=isnull(@y,0)+1
end
set nocount off
select * from @c
where (select sum(a列) from @c)=@s
/*
a列 b列
----------- --------------------
4 ewrwt
3 tyw
3 tryr
(3 row(s) affected)
*/
-- 测试2
declare @x int,@s int --输入参数
select @x=4, -- 每次随机选4条
@s=15 -- a列的和为15
set nocount on
declare @y int
declare @c table(a列 int,b列 varchar(20))
insert into @c(a列,b列)
select top(@x) a列,b列
from #t
order by newid()
while((select sum(a列) from @c)<>@s and isnull(@y,0)<=10000)
begin
delete from @c
insert into @c(a列,b列)
select top(@x) a列,b列
from #t
order by newid()
select @y=isnull(@y,0)+1
end
set nocount off
select * from @c
where (select sum(a列) from @c)=@s
/*
a列 b列
----------- --------------------
3 tryr
4 ewrwt
6 wertwertwer
2 we
(4 row(s) affected)
*/