‘壹’ 有100家客户,sql,随机取10条 ,名称前几位不一样的数据
前几位是前几位?
where条件的时候先根据首字或者名称前几位做并列排序,然后ID10个随机ID。IN完后再随机一次。
‘贰’ SQL用随机函数产生10个100—999之间的整数,分别统计出奇、偶数的个数。
declare @count int=0
declare @numbers varchar(max)=''
while(@count<10)
begin
declare @num int
set @num=CAST(FLOOR(RAND()*1000) as INT)
if(@num between 100 and 999)
begin
set @numbers=@numbers+','+CAST(@num as varchar(10))
end
else
begin
continue
end
set @count=@count+1
end
set @numbers=@numbers+','
print(@numbers)
declare @eachNumber int
declare @loopCount int
declare @evenCount int=0 --偶数
declare @oddCount int=0 --奇数
set @loopCount=LEN(@numbers)-LEN(REPLACE(@numbers,',',''))-1
set @count=0
while(@count<@loopCount)
begin
set @eachNumber=SUBSTRING(@numbers,2,CHARINDEX(',',@numbers,2)-2)
if(@eachNumber%2=0)
begin
set @evenCount=@evenCount+1;
end
else
begin
set @oddCount=@oddCount+1;
end
set @numbers=SUBSTRING(@numbers,CHARINDEX(',',@numbers,2),LEN(@numbers))
set @count=@count+1
end
print('偶数:'+cast(@evenCount as varchar(5)))
print('奇数:'+cast(@oddCount as varchar(5)))
go
测试过,正确。
‘叁’ SQL 产生10个20—99之间的随机整数
SELECT FLOOR(RAND()* 79 + 20)
用上面的sql执行,可以得出20到99之间的一个随机整数,然后你可以用循环或者重新使用10次得出10个随机数
‘肆’ SQL中随机产生10个1-50的随机整数,统计其中的基数和偶数个数
select
sum(case whe (newNumber%2)=0 then 1 else 0 end) as 偶数个数,
sum(case whe (newNumber%2)=1 then 1 else 0 end) as 奇数个数
from
(select
top 50
abs(checksum(newid())%50)+1 as newNumber
form
sysobjects a,sysobjects b
) as t1
‘伍’ 从sql server 数据库中随机取出10条记录
SELECT TOP 3 * FROM UTABLE WHERE UID='123' ORDER BY NEWID()
UNION ALL
SELECT TOP 7 * FROM UTABLE WHERE UID<>'123' ORDER BY NEWID()
说明:newid()是一个随机函数,所以这样就可以查到随机10条记录了
union all 是不消除重复记录进行连接
‘陆’ sql如何随机查询5~10条数据
SELECT * FROM 表名 WHERE sharer_id=条件(可以不写) ORDER BY RAND() LIMIT 条数
‘柒’ sql中如何随机生成5~10条数据
标准SQL语句并不支持随机查询,没有随机函数。 如果真需要这个功能,可以考虑写一个存储过程或者函数实现。