请达人,帮我举一些union的例子,我觉得没太会用

ProjectDD 2010-05-20 12:48:12
比如:

if(object_id('a') is not null) drop table a
go

create table a (col1 smalldatetime,col2 smalldatetime, col3 char(10))
go

select col1 from a order by col1
union
select col2 from a order by col2


两个order by 通不过,

顺带还有一个问题:

select top1 col1 from a
union
select top1 col1 from a order by col1 asc
--和
select top1 col1 from a
union
select top1 col1 from a order by col1 desc


这两个结果好象都是一样的 为什么呢?但 asc和 desc的结果集是不一样的得。这是怎么回事呢?

...全文
76 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
feiyanglove 2010-05-20
  • 打赏
  • 举报
回复
select * from (select top 100 percent col1 from a order by col1)a
union all
select * from (select top 100 percent col2 from a order by col2)b
feiyanglove 2010-05-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 xys_777 的回复:]
union子查询不能加order
可以外套个select
select col1 from(
select col1 from a order by col1 ) t1
union
select col2 from(
select col2 from a order by col2 ) t2
[/Quote]
你确定这样可以?
永生天地 2010-05-20
  • 打赏
  • 举报
回复
union子查询不能加order
可以外套个select
select col1 from(
select col1 from a order by col1 ) t1
union
select col2 from(
select col2 from a order by col2 ) t2

feiyanglove 2010-05-20
  • 打赏
  • 举报
回复
asc
desc
本身就不一样
既然按照这个排序
那又怎么会一样呢
feixianxxx 2010-05-20
  • 打赏
  • 举报
回复

小技巧:这时候如果你想对2输入表分别进行排序,比如上面的#a的a列升序,#b的d列降序,可以这样

select a,b
from (
select *,flag=1 from #a
union all
select *,2 from #b
) l
order by case when flag=1 then a end ,case when flag=2 then b end desc
/*
a b
----------- -----------
5 9
4 9
4 2
3 2
1 2
3 9
4 8
*/

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧