I need to create three random id between the max ID of the table and the min ID of the table. How can I do that in Sql?
Asked
Active
Viewed 410 times
-3
-
what does *max ID* and *min ID* mean exactly? By any chance, Are you trying to retrieve 3 random rows from a table? – Leo Dec 13 '17 at 02:27
-
3What have your attempted so far? – Sunil Dec 13 '17 at 02:33
-
sorry if i didn't explain myself clearly. as id, I mean the primary key of the table. I would like to select three user randomly from the table without repetition the users. i tried the use SELECT TOP 1 * FROM sch.Referee ORDER BY NEWID() but, i couldnt use it in while loop. – Yeşim Şen Dec 13 '17 at 02:46
1 Answers
2
You need to use two variables to store Min and Max primary keys. let's say @a
and @b
.
then using below query you can get your random number
declare @a int,@b int
select @b=max(id),@a=min(id)
from mytbl
SELECT FLOOR(RAND()*(@b-@a)+1)

A.D.
- 2,352
- 2
- 15
- 25

Fatemeh Sheikhha
- 66
- 5