I have one table and I want to select 10 rows randomly. But I also need to select any rows that are on "sale". I only want only 10 rows, there may be 2 sale rows there may be 9, I need to fill the remaining with random rows. I need a single query.
SELECT TOP 10 BookTitle, BookAuthor, BookCategory
FROM TheTable
ORDER BY newid()
SELECT TOP 10 BookTitle, BookAuthor, BookCategory
FROM TheTable
WHERE BookCategory LIKE 'Sale%'
I keep striking out, I may be over / under thinking this ....
Thanks.
Not very efficient for a large table but...
SELECT TOP 10 BookTitle,
BookAuthor,
BookCategory
FROM TheTable
ORDER BY CASE
WHEN BookCategory LIKE 'Sale%' THEN 0
ELSE 1
END,
newid()
If your table is large you should probably do 2 queries. One to get sale items and then the second to get the "top up" number of random non sale items only if required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With