Select Top N Random rows from table then ordering by column

时间:2015-07-28 23:49:56

标签: sql sql-server select random

I need to get 3 random rows from a table and then order those rows by a the BannerWeight column.

So if the data is:

video_28_07_2015_15_16_05.mp4_fixed.mp4

I want the results to be:

BannerID     BannerWeight
   1               5
   2               5
   3               10
   4               5
   5               10

So far I have:

BannerID     BannerWeight
   5               10
   2               5
   4               5

I just can't figure out how to order those 3 random rows once I get them. I've tried doing

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()

But this just gets me 3 random rows where the BannerWeight is 5.

Here is an SQLFiddle: http://sqlfiddle.com/#!6/a8088/2/0

1 个答案:

答案 0 :(得分:5)

Easiest option (I think) is to use a subquery:

logging.basicConfig(filename='error.log', filemode='w', level=logging.ERROR)