这个功能能否用一句sql实现?

Hrunt 2008-02-25 05:41:52
要求是:从表tab中,首先随机选取符合条件a的记录n1个,再随机选取符合条件b的记录n2个...
(设n=n1+n2+...)
以此类推,最后将选出的这n条记录随机排序

谢谢!
...全文
110 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
dobear_0922 2008-02-25
  • 打赏
  • 举报
回复
create table tab(a int, b int)

insert tab select 1,1
union all select 2,3
union all select 22,33
union all select 222,333
union all select 2222,3333
union all select 22222,33333

select * from
(
select * from (select top 2 * from tab where a>=2 order by newid()) T
union all
select * from (select top 3 * from tab where a>=33 order by newid()) T
) T
order by newid()

drop table tab

/*
a b
----------- -----------
222 333
22 33
2222 3333
2222 3333
22222 33333

(5 row(s) affected)
*/
Hrunt 2008-02-25
  • 打赏
  • 举报
回复
已解决,感谢各位!
Hrunt 2008-02-25
  • 打赏
  • 举报
回复
是第二种
但是运行了会报错~
提示:
order by 表达式 (Rnd(id)) 包含当前查询未选定的字段。只有第一次查询所包含的字段才可以包含在order by表达式中

怎么回事?
JL99000 2008-02-25
  • 打赏
  • 举报
回复
楼主把问题说明白:你的随即取法可以理解为2种情况
--第一种
先取出n1个后,将剩下的取n2个
做法:
declare @t table(各个字段)
insert into @t select top n1 * from tab where '条件a' order by Rnd(id)
insert into @t select top n2 * from tab where '条件b' and '该记录不在@t中' order by Rnd(id)


--第二种
先取出n1个,在取出n2个,做union all
这样的话会出现相同的记录
select * from
(select top n1 * from tab where '条件a' order by Rnd(id)
union all
select top n2 * from tab where '条件b' order by Rnd(id))a
order by Rnd(id)


zefuzhang2008 2008-02-25
  • 打赏
  • 举报
回复
呵呵,都被晃了
Hrunt 2008-02-25
  • 打赏
  • 举报
回复
哦,对的,非常感谢!
再补充一下,在access数据库中,没有newid()这个函数,该怎么随机查询呢?
gahade 2008-02-25
  • 打赏
  • 举报
回复
这样?

select * from (
select top n1 * from tab where a条件
union all
select top n2 * from tab where b条件)t
order by newid()
liangCK 2008-02-25
  • 打赏
  • 举报
回复
他不是问能否吗?答曰:能.
liangCK 2008-02-25
  • 打赏
  • 举报
回复
可以
pt1314917 2008-02-25
  • 打赏
  • 举报
回复

--这样?

select * from
(select top n1 * from tab where '条件a' order by newid()
union all
select top n2 * from tab where '条件b' order by newid())a
order by newid()

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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