简体   繁体   中英

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. I tried to add a WHERE clause in the code:

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:

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

Your code looks like Oracle code. 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:

SELECT TOP (10) t.*
FROM t 
WHERE columnA = 'XYZ'
ORDER BY NEWID()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM