0

I have a Products table on SQL Server. How can I select a random row from the top 10 rows - ranked by sales_count?

After finding an answer for how to select random rows, this is what I have so far:

SELECT * FROM (
    SELECT TOP 1 * FROM
        (
        SELECT TOP 10 *
        From Products
        ORDER BY "sales_count" DESC
        ) a
    ORDER BY NEWID()) b
    )

But I'm not sure it's correct?

Community
  • 1
  • 1
full_prog_full
  • 1,139
  • 10
  • 17

1 Answers1

3

There is one additional layer of subquery in your version. So assuming the columns and tables are correct, this should work:

SELECT TOP 1 p.*
FROM (SELECT TOP 10 p.*
      FROM Products p
      ORDER BY "sales_count" DESC
     ) p
ORDER BY NEWID();

If you wanted to be fair, you might add WITH TIES:

SELECT TOP (1) p.*
FROM (SELECT TOP (10) WITH TIES p.*
      FROM Products p
      ORDER BY "sales_count" DESC
     ) p
ORDER BY NEWID();
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786