union order by newid()不能一起用,请高手来看看!

flcandclf 2006-09-09 01:22:59
select top 3 * from a where type = 1 union select top 2 * from a where type = 1可以实现,
但我想满足type=1的随机取3条数据,满足type=1的取随机2条数据怎么实现?
用select top 3 * from a where type = 1 order by newid() union select top 2 * from a where type = 1 order by newid()
就出错,望高手给点指点,谢谢!
...全文
285 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
flcandclf 2006-09-15
  • 打赏
  • 举报
回复
谢谢lxzm1001(*悠悠蓝星*)的解答,已经解决此问题了,同时也谢谢大家的回复!
flcandclf 2006-09-10
  • 打赏
  • 举报
回复
谢谢大家的回复,我回去再试!
yaoyaomaomao 2006-09-10
  • 打赏
  • 举报
回复
楼上正解
中国风 2006-09-10
  • 打赏
  • 举报
回复

select *
from (select top 3 * from a where type = 1 order by newid())a
union all
select *
from (select top 2 * from a where type = 1 order by newid())b
这样为可以了
zicxc 2006-09-09
  • 打赏
  • 举报
回复
select * from (
select * from (
select top 3 * from a where type = 1 order by newid()
) as t1
union all
select * from (
select top 2 * from a where type = 2 order by newid()
) as t2
) as t
lxzm1001 2006-09-09
  • 打赏
  • 举报
回复
select * from (
select * from (
select top 3 * from a where type = 1 order by newid()
) as t1
union all
select * from (
select top 3 * from a where type = 2 order by newid()
) as t2
)p
flcandclf 2006-09-09
  • 打赏
  • 举报
回复
分析查询不报错,但一执行查询就出错了!
flcandclf 2006-09-09
  • 打赏
  • 举报
回复
服务器: 消息 104,级别 15,状态 1,行 1
如果语句中包含 UNION 运算符,那么 ORDER BY 子句中的项就必须出现在选择列表中。
按照楼上的做法,还是报这样的错误,怎么会事啊,还望楼上的高手指点!
zicxc 2006-09-09
  • 打赏
  • 举报
回复
想满足type=1的随机取3条数据,满足type=1的取随机2条数据怎么实现?

是不是输入错误

想满足type=1的随机取3条数据,满足type=2的取随机2条数据怎么实现?


select * from (
select top 3 * from a where type = 1 order by newid()
) as t1
union all
select * from (
select top 2 * from a where type = 2 order by newid()
) as t2

xyxfly 2006-09-09
  • 打赏
  • 举报
回复
楼上正解了
zicxc 2006-09-09
  • 打赏
  • 举报
回复
select * from (
select top 3 * from a where type = 1 order by newid()
) as t1
union all
select * from (
select top 2 * from a where type = 1 order by newid()
) as t2
flcandclf 2006-09-09
  • 打赏
  • 举报
回复
给还有其他的办法实现啊,只要满足type=1的随机取3条数据,满足type=1的取随机2条数据就行
flcandclf 2006-09-09
  • 打赏
  • 举报
回复
这样也不对啊,报错是说如果语句中包含union运算符,那么order by 子句中的项就必须出现在选择列表中
mugua604 2006-09-09
  • 打赏
  • 举报
回复
union 前不可以用ORDER BY
xiaomeixiang 2006-09-09
  • 打赏
  • 举报
回复
前面不能用: order by newid()
select top 3 * from a where type = 1union select top 2 * from a where type = 1 order by newid()

34,590

社区成员

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

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