MortezaJ
MortezaJ

Reputation: 13

Select randomly And Sort the records

I have a table which has ID,name and Level columns.I want to SELECT the records of the Table by this pattern : First Select Them randomly and then sort those random records by level column.

for example : my sample table and records:

ID      name         Level
--------------------------------- 
1      red-book         1
2      blue-pen         10
3      black-board      12
4      balck-Book       1
5      white-book       1
6      red-pen          10
7      green-pen        10

And the result should be something like this :

ID            name             level
------------------------------------------
3             black-board      12
6             red-pen          10
2             blue-pen         10
7             green-pen        10
4             balck-Book       1
1             red-book         1
5             white-book       1

I've also used

 SELECT * FROM MyTable ORDER BY NEWID(),Level DESC

And

 SELECT * FROM 
 (SELECT * FROM MyTable ORDERBY NEWID())As TempTbl 
 ORDER BY Level DESC

And

 CREATE TABLE #MyTempTable (ID INT,name Nvarchar(256),Levels INT)

 INSERT INTO #MyTempTable SELECT * FROM MyTable ORDER BY NEWID()

 SELECT * FROM #MyTempTable ORDER BY Levels DESC

Upvotes: 1

Views: 220

Answers (1)

Wietze314
Wietze314

Reputation: 6020

SELECT ID,name,level
FROM sample
ORDER BY level DESC,NEWID()

Upvotes: 2

Related Questions