Reputation: 2534
My database has 5 categories in table "category". I also have a table called "items", where each item has unique Id and a category Id FK.
I need to randomly select 10 items from 1 category.
This would not be problem if there was only 1 category. But table "items" stores categories id in non-sequential order.
The random select statement below works and is able to generate random IDs within a range. But how can I generate 10 random IDs that belong to the same category?
Declare @maxRandomValue tinyint = 100
, @minRandomValue tinyint = 0;
Select Cast(((@maxRandomValue + 1) - @minRandomValue)
* Rand() + @minRandomValue As tinyint) As 'randomNumber';
Defintions:
Table Categories
ID INT
Desc Varchar(100)
Table Items
ID Int
CategoryID Int (fk)
Desc Varchar(100)
Upvotes: 2
Views: 691
Reputation: 432421
Use
So:
SELECT TOP 10
*
FROM
Items
WHERE
CategoryID = @whatever
ORDER BY
NEWID()
Upvotes: 6
Reputation: 44336
select top 10 * from items where categoryid = 1 order by newid()
Upvotes: 5