Select DB2 中的前几行和按 NEWID() 排序

Select Top rows and Order by NEWID() in DB2

在SQL服务器中,我有这个查询

SELECT TOP 10 * 
FROM xTable
ORDER BY NEWID()

这基本上是 returns 10 个随机行。我还有用数字参数化的顶行,但这不是问题

我想在 DB2 查询中执行此操作,因为我必须使用 OpenQuery 从 DB2 获取数据并存储在本地临时文件 table 中,然后我从中执行 select 前 x 行。

如果我可以直接在 DB2 中实现这一点,那就太棒了,因为我必须处理超过一千行。

这是 DB2 LUW 还是 AS400?

尝试

SELECT *
  FROM xTable
  ORDER BY ROW_NUMBER()
  FETCH FIRST 10 ROWS ONLY;

排序不是一个好主意,尤其是对于大表。
我们有能力将 built-in Db2 用于 subselect - tablesample-clause 的 LUW 功能。

BERNOULLI

BERNOULLI sampling considers each row individually. It includes each row in the sample with probability P/100 (where P is the value of numeric-expression1), and excludes each row with probability 1 - P/100, independently of the other rows. So if the numeric-expression1 evaluated to the value 10, representing a ten percent sample, each row would be included with probability 0.1, and excluded with probability 0.9.

SYSTEM

SYSTEM sampling permits the database manager to determine the most efficient manner in which to perform the sampling. In most cases, SYSTEM sampling applied to a table-name means that each page of table-name is included in the sample with probability P/100, and excluded with probability 1 - P/100. All rows on each page that is included qualify for the sample.

示例:

SELECT * 
FROM MYTABLE TABLESAMPLE SYSTEM (0.1) 
FETCH FIRST 10 ROWS ONLY;

此功能在 DB2 for IBM i/iSeries/OS400 中不存在。请改用此平台的 order by rand() fetch first 10 rows 子句。