TSQL Random Select with Selective Criteria
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)
Use
- a WHERE to filter to a category
- NEWID to randomise rows
- TOP to limit you to 10 items
So:
SELECT TOP 10
*
FROM
Items
WHERE
CategoryID = @whatever
ORDER BY
NEWID()
select top 10 * from items where categoryid = 1 order by newid()
精彩评论