Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从表中选择前N个随机行,然后按列排序_Sql_Sql Server_Select_Random - Fatal编程技术网

Sql 从表中选择前N个随机行,然后按列排序

Sql 从表中选择前N个随机行,然后按列排序,sql,sql-server,select,random,Sql,Sql Server,Select,Random,我需要从一个表中随机获得3行,然后在BannerWeight列中按顺序排列这些行 因此,如果数据是: BannerID BannerWeight 1 5 2 5 3 10 4 5 5 10 我希望结果是: BannerID BannerWeight 5 10 2

我需要从一个表中随机获得3行,然后在BannerWeight列中按顺序排列这些行

因此,如果数据是:

BannerID     BannerWeight
   1               5
   2               5
   3               10
   4               5
   5               10
我希望结果是:

BannerID     BannerWeight
   5               10
   2               5
   4               5
到目前为止,我已经:

SELECT TOP 3 b.BannerID, b.BannerWeight FROM CMS_Banner b
INNER JOIN CMS_BannerCategory c ON b.BannerCategoryID = c.BannerCategoryID
WHERE c.BannerCategoryName LIKE 'HomepageSponsors'
ORDER BY NEWID()
我就是想不出一旦我得到了那3个随机的行,该如何排序。我试过了

 ORDER BY BannerWeight, NEWID()
但这只是得到了3个随机行,其中横幅权重为5

这里有一个SQLFIDLE:

最简单的选择(我认为)是使用子查询:

Select * from 
    (
    SELECT TOP 3 b.BannerID, b.BannerWeight FROM Banners b
    ORDER BY NEWID()
    ) a
order by a.bannerweight

这似乎奏效了。我就是搞不懂子查询