一个排序的小问题,百思不得其解

文盲老顾
WEB应用领新星创作者
博客专家认证
2020-10-20 11:30:07

with t as (
select 'aa' as a
union all select 'bb'
union all select 'xbb'
union all select 'fbb'
union all select 'ebb'
union all select 'tqbb'
union all select 'zzbb'
union all select 'aaabb'
union all select 'fefbb'
),t1 as (
select top 3 * from t order by newid()
)
select * from t1
outer apply (
select top 2 a as sub
from t x
where not exists(select top 1 1 from t1 f where f.a=x.a)
order by newid()
) x


现在有一个小表格,里面有一些数据,想从里面随机提取出3个项目,然后,提取出的项目,随机分配2个剩余的项目,且不得重复

目前我进行到随机分配剩余项目,重复不重复且不说,为什么按照我的这个sql,剩余子项目分配完全一致?

如果要实现我的需求,应该怎么写这个指令?
...全文
185 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
文盲老顾 2020-10-20
  • 打赏
  • 举报
回复
declare @tb table(a varchar(20))
insert into @tb
select '1aa' as a
union all select '2bb'
union all select '3xbb'
union all select '4fbb'
union all select '5ebb'
union all select '6tqbb'
union all select '7zzbb'
union all select '8aaabb'
union all select '9fefbb'
select top 3 a,0 as lv into #t1 from @tb order by newid()
select *,1 as lv 
into #t2
from @tb b
where not exists(select top 1 1 from #t1 where a=b.a)
select * from #t1,#t2
drop table #t1
drop table #t2
使用临时表就没有这个问题。。。这是什么原因?
文盲老顾 2020-10-20
  • 打赏
  • 举报
回复
with t as (
	select '1aa' as a
	union all select '2bb'
	union all select '3xbb'
	union all select '4fbb'
	union all select '5ebb'
	union all select '6tqbb'
	union all select '7zzbb'
	union all select '8aaabb'
	union all select '9fefbb'
),t1 as (
	select top 3 a,0 as lv from t order by newid()
),t2 as (
	select *,1 as lv 
	from t b
	where not exists(select top 1 1 from t1 where a=b.a)
)
select * from t1,t2
一个更简单的测试,t1表提出三个项目,t2表应该是剩余的项目,但现在t1、t2联合查询,发现t2中出现了t1的项目,这就很奇怪了
lich2005 2020-10-20
  • 打赏
  • 举报
回复
在你代码的基础小改一下。


declare @tb table(a varchar(20), b int);
--------------------------------
with t as (
	select '1aa' as a
	union all select '2bb'
	union all select '3xbb'
	union all select '4fbb'
	union all select '5ebb'
	union all select '6tqbb'
	union all select '7zzbb'
	union all select '8aaabb'
	union all select '9fefbb'
)
--------------------------------

insert into @tb(a, b)
select top 3 a,0 as lv  from t order by newid();

with t as (
	select '1aa' as a
	union all select '2bb'
	union all select '3xbb'
	union all select '4fbb'
	union all select '5ebb'
	union all select '6tqbb'
	union all select '7zzbb'
	union all select '8aaabb'
	union all select '9fefbb'
)

select *,1 as lv 
into #t2
from t
where not exists(select top 1 1 from @tb a where a.a=t.a)

select * from @tb,#t2

--drop table #t2

lich2005 2020-10-20
  • 打赏
  • 举报
回复
因为 t2 去匹配的时候,t1 的那3个随机数可能已经不是“原来的”那3个随机数了,你可以理解为 t1 的取值对于 t2 来说更像是变量,而不是静态值。 临时表就没有这样的问题了,取完值存放里面的都是静态数值。

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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