[英]Is there a simple way to pick random records (about 20) from a data table with specific condition
Here is the code I used这是我使用的代码
SELECT * FROM
(SELECT * FROM [table name]
ORDER BY dbms_random.value)
WHERE rownum < 10
I would like to select random rows only from records with column A = XYZ.我只想从列 A = XYZ 的记录中选择随机行。 I tried to add a WHERE clause in the code:我试图在代码中添加一个 WHERE 子句:
SELECT * FROM
(SELECT * FROM [table name]
WHERE [column A] = 'XYZ'
ORDER BY dbms_random.value)
WHERE rownum < 10
but got an error.但出现错误。 Any feedback would be greatly appreciated.任何反馈将不胜感激。
You can try the below approach in SQL Server:您可以在 SQL Server 中尝试以下方法:
SELECT TOP 10 * FROM [table name]
WHERE [column A] = 'XYZ'
ORDER BY newid()
More information on how ORDER BY newid() works in a SO post 有关 ORDER BY newid() 如何在 SO 帖子中工作的更多信息
Your code looks like Oracle code.您的代码看起来像 Oracle 代码。 It does not recognize square braces for identifiers.它不识别标识符的方括号。 In fact, don't escape them -- or use double quotes if you must:事实上,不要转义它们——或者如果必须的话使用双引号:
SELECT t.*
FROM (SELECT t.*
FROM t
WHERE columnA = 'XYZ'
ORDER BY dbms_random.value
) t
WHERE rownum < 10;
In SQL Server, the equivalent would be:在 SQL Server 中,相当于:
SELECT TOP (10) t.*
FROM t
WHERE columnA = 'XYZ'
ORDER BY NEWID()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.