我在SQL Server上有一个Products表。如何从前10行中选择一个随机行 - 按sales_count排名?
在找到如何select random rows的答案之后,这就是我到目前为止所做的:
SELECT * FROM (
SELECT TOP 1 * FROM
(
SELECT TOP 10 *
From Products
ORDER BY "sales_count" DESC
) a
ORDER BY NEWID()) b
)
但我不确定这是对的吗?
答案 0 :(得分:3)
您的版本中还有一个额外的子查询图层。因此,假设列和表是正确的,这应该有效:
SELECT TOP 1 p.*
FROM (SELECT TOP 10 p.*
FROM Products p
ORDER BY "sales_count" DESC
) p
ORDER BY NEWID();
如果您想公平,可以添加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();