Access开发培训
网站公告
·Access专家课堂QQ群号:151711184    ·Access快速开发平台下载地址及教程    ·欢迎加入Access专家课堂微信群!    ·如何快速搜索本站文章|示例|资料    
您的位置: 首页 > 技术文章 > Access数据库-查询/SQL语句

【译文】选择最前记录的查询

时 间:2012-04-10 11:44:18
作 者:周芳   ID:24526  城市:上海
摘 要:用一个查询从一个表中选择最前N条记录。
正 文:

原作者:未知  翻译:周芳

【译文】选择前N条记录的例子

      你曾经有需要用一个查询从一个表中只获取前三条记录的经历吗?

      那么,如果你想知道如何去做,这里就有一个选择最前记录查询的解决方案:


1) 创建一个查询(Query1)来获得前三名的记录,在“M_Revisions”表中的“Submit_Date”字段

      Select Top 3 M_Revisions.Submit_Date from M_Revisions order by M_Revisions.Submit_Date
      选择前3条记录 从M_Revisions表中(按Submit_Date升序)。

2) 使用Query1作为数据源生成一个新的查询

      Select Top 1 Query1.Submit_Date from Query1 order by Query1.Submit_Date DESC
      选择第1行记录,在查询Query1中(按字段Submit_Date降序排列)

      现在你就得到了第3个“提交日期”值,注意,这个新的Query1查询让这三条记录按照降序排序然后就使得第三条记录跑到第一位。

      你可以使用“Select Top”检索任何数量的记录,比如:

      Select Top 10 选择前10条信息

      Select Top 100 选择前100条信息

      Select Top 123 选择前123条信息

      如上所示,你可以分组后用排序选项 (group by)来选择适当的最前记录。在你的查询中,你可以把这个跟标量查询选项联合起来来完成复杂的操作。(注:标量查询,查询可以在select子句中指定类的属性。甚至可以调用SQL的统计函数。)

      使用"select top"选择最前记录并非没有问题。我们已经注意到有一个bug,当你选择查询20到30个字符的长文本字段时,基于最高纪录查询的一些问题,文本数据也是一样的。例如,如果你选择前100记录,你可能会得到110记录。

【原文】

Select Top Query

Select Top n Records Predicate Example

Have you ever had the need to get the 3rd record from a table using a query only?

Well, in case you want to know how to do it here is the select top records query solution:

1) Create a query (Query1) to get the top three records.  We are interested in field called Submit_Date from a table

Select Top 3 M_Revisions.Submit_Date from M_Revisions order by M_Revisions.Submit_Date;

2) Use Query1 as input to a new query:

Select Top 1 Query1.Submit_Date from Query1 order by Query1.Submit_Date DESC;

Now you have the 3rd submit date.  Note that sorting the Query1 records in descending order makes the 3rd record go to the top.

You can use Select Top query to retrieve any number of records such as:

Select Top 10

Select Top 100

Select Top 123

As shown above you can use the sort option (Group By) to arrange the records in the order you want to select the appropriate top records.  You can combine this with the scalar query option to perform complex operations with your queries.

The select top query is not without its problems.  We have noticed a bug in the select top predicate query when you are selecting from long text fields where the first 20 to 30 characters are the same in the text data.  For instance, if you use Select Top 100 you may get back 110 records.



Access软件网QQ交流群 (群号:483923997)       Access源码网店

常见问答:

技术分类:

相关资源:

专栏作家

关于我们 | 服务条款 | 在线投稿 | 友情链接 | 网站统计 | 网站帮助