本文介紹了帶有選擇性標準的 TSQL 隨機選擇的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我的數據庫在category"表中有 5 個類別.我還有一個名為items"的表,其中每個項目都有唯一的 Id 和一個類別 Id FK.
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.
我需要從 1 個類別中隨機選擇 10 個項目.
I need to randomly select 10 items from 1 category.
如果只有 1 個類別,這不會有問題.但是表items"以非順序存儲類別id.
This would not be problem if there was only 1 category. But table "items" stores categories id in non-sequential order.
下面的隨機選擇語句有效并且能夠在一個范圍內生成隨機 ID.但是如何生成 10 個屬于同一類別的隨機 ID?
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';
定義:
Table Categories
ID INT
Desc Varchar(100)
Table Items
ID Int
CategoryID Int (fk)
Desc Varchar(100)
推薦答案
使用
- 過濾類別的 WHERE
- 新增隨機行
- TOP 限制您最多 10 個項目
所以:
SELECT TOP 10
*
FROM
Items
WHERE
CategoryID = @whatever
ORDER BY
NEWID()
這篇關于帶有選擇性標準的 TSQL 隨機選擇的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!