句を発見したばかりですTABLESAMPLE
が、驚くべきことに、指定した行数が返されません。
私が使用したテーブルには約 14M 行があり、10000 行の任意のサンプルが必要でした。
select * from tabData TABLESAMPLE(10000 ROWS)
10000 ではなく、実行するたびに異なる数値 (8000 から 14000 の間) を取得します。
ここで何が起こっているのですか? の意図された目的を誤解していTABLESAMPLE
ますか?
編集:
デビッドのリンクはそれをかなりよく説明しています。
これは、効率的な方法で常に 10000 個のほぼランダムな行を返します。
select TOP 10000 * from tabData TABLESAMPLE(20000 ROWS);
このREPEATABLE
オプションは、常に同じものを取得するのに役立ちます(データが変更されていない限り)
select TOP 10000 * from tabData TABLESAMPLE(10000 ROWS) REPEATABLE(100);
TABLESAMPLE
正しい行番号を取得するために (?) 多数の行を使用する方がコストがかかるかどうかを知りたかったので、測定しました。
1.ループ(20回):
select TOP 10000 * from tabData TABLESAMPLE(10000 ROWS);
(9938 row(s) affected)
(10000 row(s) affected)
(9383 row(s) affected)
(9526 row(s) affected)
(10000 row(s) affected)
(9545 row(s) affected)
(9560 row(s) affected)
(9673 row(s) affected)
(9608 row(s) affected)
(9476 row(s) affected)
(9766 row(s) affected)
(10000 row(s) affected)
(9500 row(s) affected)
(9941 row(s) affected)
(9769 row(s) affected)
(9547 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(9478 row(s) affected)
First batch(only 10000 rows) completed in: 14 seconds!
2.ループ(20回):
select TOP 10000 * from tabData TABLESAMPLE(10000000 ROWS);
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
Second batch(max rows) completed in: 13 seconds!
3.ループ: ORDER BY NEWID() を使用して 100% ランダムな行でカウンターチェック:
select TOP 10000 * from tabData ORDER BY NEWID();
(10000 row(s) affected)
23 分間の 1 回の実行後にキャンセルされました
結論:
したがって、驚くべきことに、exactTOP
句と多数の in を使用したアプローチは遅くTABLESAMPLE
はありません。ORDER BY NEWID()
したがって、行が行ごとにランダムではなく、ページ レベルごとにランダムであることが問題にならない場合 (テーブルの各 8K ページにはランダムな値が与えられます)の非常に効率的な代替手段です。