简体   繁体   中英

How to select 20 random questions from each set in sql?

I am working on online question application.

I am Fetching Records from a database .

I have SQL database holding 1000 question in 10 set. I mean each set containing 100 questions. How can I take 20 random questions from each set? I mean how can I select 2 (as per request) random question from each set?

Try:

SELECT TOP 20 * FROM [YourTable] ORDER By NEWID()

More About NEWID() .

If you need to get 20 random questions from each group here is an SQLFiddle example . SetNum here is a set ID

select * from 
(
select t.*, 
ROW_NUMBER() 
over (partition by setNum order by NewId()) rNum from t
) t2 where rNum<=20

Try this if you want 2 random questions from each SET...

SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 1) ORDER By NEWID()
UNION
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 2) ORDER By NEWID()
UNION
.
.
.
.
UNION
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 10) 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