简体   繁体   中英

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
SELECT ID,name,level
FROM sample
ORDER BY level DESC,NEWID()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM