我想選擇前10行,然後選擇它們的5個隨機行。選擇前10行,然後選擇它們的5個隨機行
4
A
回答
6
必須在此代碼段中定義「前10個」,它是「某件事」。這是SQL Server 2000 +
select top 5
*
from
(
select top 10 * from <table>
order by something --got to have soemthing here to define "first 10"
) as a
order by
newid()
編輯:
爲什麼你需要ORDER BY派生表
-- large row, same result with and without index/PK
CREATE TABLE #foo (bar int /*PRIMARY KEY NONCLUSTERED (bar)*/, eejit char(8000))
--create rows with value 1-10 + some others
INSERT #foo (bar) VALUES (1)
INSERT #foo (bar) VALUES (10)
INSERT #foo (bar) VALUES (20)
INSERT #foo (bar) VALUES (2)
INSERT #foo (bar) VALUES (5)
INSERT #foo (bar) VALUES (45)
INSERT #foo (bar) VALUES (99)
INSERT #foo (bar) VALUES (3)
INSERT #foo (bar) VALUES (9)
INSERT #foo (bar) VALUES (7)
INSERT #foo (bar) VALUES (6)
INSERT #foo (bar) VALUES (4)
INSERT #foo (bar) VALUES (8)
--create logical fragmentation
DELETE #foo WHERE bar IN (1, 3, 5, 7, 9)
INSERT #foo (bar) VALUES (1)
INSERT #foo (bar) VALUES (3)
INSERT #foo (bar) VALUES (5)
INSERT #foo (bar) VALUES (7)
INSERT #foo (bar) VALUES (9)
-- run this a few times, you will see values > 10
-- "first 10" surely means values between 1 and 10?
select top 5
*
from
(
select top 10 * from #foo
) as a
order by
newid()
-- always <= 10 because of ORDER BY
select top 5
*
from
(
select top 10 * from #foo
order by bar --got to have soemthing here to define "first 10"
) as a
order by
newid()
1
2
select *
from
(select * from table order by id limit 10) as rows order by rand() limit 5
相關問題
- 1. MySQL的 - 選擇特定的行,然後才隨機他們
- 2. 選擇隨機行
- 3. SQL - 僅選擇前10行?
- 4. 選擇之前未被選擇的隨機行嗎?
- 5. MySQL在查詢後選擇前5行
- 6. SQL選擇隨機行,但不會在下次重新選擇它們
- 7. 選擇前50行,然後訂購
- 8. UITableView多選。自動選擇行隨機選擇行
- 9. MySQL選擇有序的行,然後隨機化結果
- 10. 從日期中選擇10行向前和10個向後
- 11. 選擇5個隨機元素
- 12. 以隨機順序選擇行,然後將其顛倒
- 13. Spark DataFrame - 選擇n個隨機行
- 14. 選擇最後5個MySQL行
- 15. Datagridview行不可見,行選擇隨機
- 16. 從Python中的前一個選擇中隨機選擇
- 17. 如何選擇TOP 5,然後選擇以下5?
- 18. 隨機選擇
- 19. 隨機選擇
- 20. 隨機選擇
- 21. 先選擇一行,然後再選擇第二行
- 22. 是否可以一次選擇一個隨機文檔,然後再不選擇?
- 23. 選擇前5個唯一行,在SQL Server 2005中隨機排序?
- 24. 隨機選擇相鄰行的組
- 25. PHP MySQL的隨機選擇行
- 26. 隨機地從行的子集選擇
- 27. 不同概率的隨機行選擇
- 28. 更新隨機選擇的行
- 29. R - 隨機選擇變量並按行對它們進行操作
- 30. 如何隨機選擇一個數組,然後在javaScript中隨機選擇一個元素?
這很好。你有什麼更多的背景來解決你的問題嗎? – Oded 2010-12-06 11:20:56
所以你想要選擇前10行的5個隨機行? :) – Pabuc 2010-12-06 11:21:11
是的,這是正確的pabuc – Arrabi 2010-12-06 11:21:59