请大家帮忙看一个SQL语句,关于Union 和Order by

mingjunr 2003-07-29 11:58:32
select top 2 * from Customers where city='London' order by newid()
union
select top 3 * from Customers where city='Bern' order by newid()
看上面这个语句该怎么写?上面的写法是错误的
意图如下:
在顾客表里随机抽两个london的客人和3 个Bern的客人!!
...全文
91 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2003-07-29
  • 打赏
  • 举报
回复
这个问题在我的方法里已经避免了.
sdhdy 2003-07-29
  • 打赏
  • 举报
回复
order by newid()和union无法连用
try:
select top 2 * into #temp from Customers where city='London' order by newid()
insert #temp select top 3 * from Customers where city='Bern' order by newid()
select * from #temp
drop table #temp
happydreamer 2003-07-29
  • 打赏
  • 举报
回复
select coloumnlist (except newid) from (select top 2 *,newid() a from Customers where city='London' order by newid()) tem
union all
select coloumnlist (except newid) from (select top 3 *,newid() from Customers where city='Bern' order by newid()) tem2


otherwise your will get error message
如果语句中包含 UNION 运算符,那么 ORDER BY 子句中的项就必须出现在选择列表中

sdhdy 2003-07-29
  • 打赏
  • 举报
回复
select * from (select top 2 * from Customers where city='London' order by newid()) aa
union all
select * from (select top 3 * from Customers where city='Bern' order by newid()) bb
woyaofengle 2003-07-29
  • 打赏
  • 举报
回复
你到底是要随机 还是要头两个
zjcxc 元老 2003-07-29
  • 打赏
  • 举报
回复
select * from
(select top 2 *,newid() as temp_id from syscolumns where name<>'London' order by newid()) a
union
select * from
(select top 3 *,newid() as temp_id from syscolumns where name<>'Bern' order by newid()) b
pengdali 2003-07-29
  • 打赏
  • 举报
回复
select * from (select top 2 * from Customers where city='London' order by newid()) tem
union all
select * from (select top 3 * from Customers where city='Bern' order by newid()) tem2
hjb111 2003-07-29
  • 打赏
  • 举报
回复
写出一下错误信息!
txlicenhe 2003-07-29
  • 打赏
  • 举报
回复
Select * from (select top 2 * from Customers where city='London' order by newid()) a
union
select * from (select top 3 * from Customers where city='Bern' order by newid()) b
CrazyFor 2003-07-29
  • 打赏
  • 举报
回复
看不出上面的有什么问题啊,怎么错了?
erigido 2003-07-29
  • 打赏
  • 举报
回复
学习,确实很巧妙啊
nboys 2003-07-29
  • 打赏
  • 举报
回复
select * from (select top 2 * from Customers where city='London' order by newid()) a

union all

select * from (select top 3 * from Customers where city='Bern' order by newid()) b

34,590

社区成员

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

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