【问题标题】:Select Top N Random rows from table then ordering by column从表中选择前 N 个随机行,然后按列排序
【发布时间】:2015-10-19 18:12:34
【问题描述】:

我需要从表中随机获取 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 个随机行,其中 BannerWeight 为 5。

这是一个 SQLFiddle:http://sqlfiddle.com/#!6/a8088/2/0

【问题讨论】:

    标签: sql sql-server select random


    【解决方案1】:

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

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

    【讨论】:

    • 这似乎可以解决问题。我就是想不通子查询
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多