当前位置:asp编程网>技术教程>Database教程>  正文

一条sql语句实现合并两个查询结果

1970-01-01 08:00:00   来源:www.aspprogram.cn    作者:wangsdong   浏览量:5645   收藏

'功能:一条sql语句实现合并两个查询结果
'作者:wangsdong
'来源:www.aspprogram.cn
'原创文章,转载请保留此信息,谢谢。

表名:table
字段:ID  username ytime
需要实现的结果是:
查询1:
   select top 5 * from table where Id>20 order by id asc
查询2:
   select top 5 * from table where id<20 order by id desc
并且再将查询1和查询2之和,再按照ID的倒序。原以为:查询2好办,本来就倒序了,并且都小于20,所以这个不需要改动的。现在需要再将查询1进行一次排序就行了。
于是写了一个sql语句:
select * from (select top 5 * from table where Id>20 order by id asc) order by id desc
union all
select top 5 * from table where Id>20 order by id asc
运行的结果居然是:id>20的那5条记录没有倒序。

必须换种写法了:
select * from (select top 5 * from table where Id>20 order by id asc
union all
select top 5 * from table where Id>20 order by id asc) order by id desc
思路是:先将两个查询合并到一起,然后再进行倒序。终于搞定了。



关于我们-广告合作-联系我们-积分规则-网站地图

Copyright(C)2013-2017版权所属asp编程网