- ·上一篇文章:两表联合查询的sql删除语句的写法
- ·下一篇文章:SQL Server中RAISERROR的具体用法详解
一条sql语句实现合并两个查询结果
'功能:一条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
思路是:先将两个查询合并到一起,然后再进行倒序。终于搞定了。
一条sql语句实现合并两个查询结果