随机选择并对记录排序

时间:2013-09-25 11:20:33

标签: sql sql-server random

我有一个具有ID,名称和级别列的表。我想通过这种模式选择表的记录: 首先随机选择它们,然后按级别列对这些随机记录进行排序。

例如:我的样本表和记录:

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

结果应该是这样的:

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

我也用过

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

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

 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

1 个答案:

答案 0 :(得分:2)

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