首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

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

2012-04-12 
请达人,帮我举一些union的例子,我觉得没太会用比如:if(object_id(a) is not null) drop table agocreate

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

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的结果集是不一样的得。这是怎么回事呢?



[解决办法]
asc
desc
本身就不一样
既然按照这个排序
那又怎么会一样呢
[解决办法]
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


[解决办法]

探讨
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

[解决办法]
SQL code
select * from (select top 100 percent col1 from a order by col1)aunion allselect * from (select top 100 percent col2 from a order by col2)b
[解决办法]
SQL code
小技巧:这时候如果你想对2输入表分别进行排序,比如上面的#a的a列升序,#b的d列降序,可以这样select a,bfrom (select *,flag=1 from #aunion allselect *,2 from #b) lorder by case when flag=1 then a  end ,case when flag=2 then b end desc /*a           b----------- -----------5           94           94           23           21           23           94           8*/ 

热点排行