使用联合从 MS Access 表中选择随机记录 [重复]

Posted

技术标签:

【中文标题】使用联合从 MS Access 表中选择随机记录 [重复]【英文标题】:Selecting random records from MS Access table With Union [duplicate] 【发布时间】:2018-02-21 13:11:20 【问题描述】:

我正在尝试从 3 个不同组/存储桶的 Access 表中收集随机记录样本。在我的示例中,我希望每个 [Duration of the Call] 存储桶中有 50 条随机记录,总共 150 条记录。我用一个 UNION 子句加入每个组。返回的结果不是随机的,每个 50 个存储桶只是从 2018 年 1 月 2 日的第一个调用日期中提取的。就像 TOP 子句只是查看表中与条件匹配的前 50 条记录,但我想要从整个表中真正随机抽样。谢谢

SELECT * FROM ( 
SELECT TOP 50
 [Workgroup],[Last Name],[First Name],[Titanium Number],
[Phone Number], [Inbound-Outbound], [Date of the Call], [Time of the Call], 
[Duration of the Call], ID 
FROM PCA_Calls WHERE 
([Date of the Call] >=  #1/1/2018# ) AND 
([Date of the Call] <=  #1/31/2018# ) AND 
([Duration of the Call] >= 420) AND ([Duration of the Call] <=900) AND 
([Workgroup] =  "PCA0001A" ) 

UNION 
SELECT TOP 50
 [Workgroup],[Last Name],[First Name],[Titanium Number],
[Phone Number], [Inbound-Outbound], [Date of the Call], [Time of the Call], 
[Duration of the Call], ID 
FROM PCA_Calls WHERE 
([Date of the Call] >=  #1/1/2018# ) AND 
([Date of the Call] <=  #1/31/2018# ) AND 
([Duration of the Call] >= 901) AND ([Duration of the Call] <=1800) AND 
([Workgroup] =  "PCA0001A" ) 

UNION 
SELECT TOP 50
 [Workgroup],[Last Name],[First Name],[Titanium Number],
[Phone Number], [Inbound-Outbound], [Date of the Call], [Time of the Call], 
[Duration of the Call], ID 
FROM PCA_Calls WHERE 
([Date of the Call] >=  #1/1/2018# ) AND 
([Date of the Call] <=  #1/31/2018# ) AND 
([Duration of the Call] >= 1801) AND ([Duration of the Call] <=2700) AND 
([Workgroup] =  "PCA0001A" ) 
) AS Sub ORDER BY rnd(INT(NOW*ID)-NOW*ID);enter code here

【问题讨论】:

将顺序移动到联合中的每个查询 这些建议都不起作用 如果某些东西不起作用,请说明您是如何应用它的,以及您的意思是什么不起作用。您是否收到错误、意外结果等 将 ORDER BY 添加到 UNION 中的每个查询都会产生错误“ORDER BY 表达式 (Rnd(-1000*ID)*Time())) 包含查询未选择的字段. 只有在第一个查询中请求的那些字段才能包含在 ORDER BY 表达式中”。使用 UNION 时只能有 1 个 ORDER BY。 只需使用子查询来避免该错误。 (SELECT * FROM (SELECT TOP 50 etc FROM something ORDER BY something)) 【参考方案1】:

删除外部随机排序并将其应用于每个查询。

另外,修改表达式以进行排序,如下所示:

Random sorting query Access

【讨论】:

这会产生错误“产生错误”ORDER BY 表达式 (Rnd(-1000*ID)*Time())) 包含查询未选择的字段。只有第一个查询中请求的字段才能包含在 ORDER BY 表达式中" 哦,你是对的,就是这样。您可能需要创建三个(子)查询,每个查询抽取 50 条随机记录,然后将这三个查询合并到一个普通的联合查询中。

以上是关于使用联合从 MS Access 表中选择随机记录 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

使用 MSSQL Server 从 MS ACCESS 数据库中选择数据记录

MS Access - 根据百分比随机选择记录

MS Access 2007 - 选择多条记录并将值分配给字段

MS Access:从没有外键的 2 个表中选择记录

我可以使用文本框引用来选择 MS Access 中的特定记录吗

从两个日期之间的 MS Access 表中选择?