gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:44:04 26 4
gpt4 key购买 nike

我需要从表中随机获取 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

最佳答案

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

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

关于sql - 从表中选择前 N 个随机行,然后按列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31689009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com