日期:2014-05-17  浏览次数:20494 次

高分求实现sql 语句,详见帖子
有两张表:Tab_A和Tab_B,字段如下:

Tab_A;
id   time other
Tab_B:
id   time other

现在要求实现的功能:
分别查询查询Tab_A和Tab_B,放到一个记录集中。
要求:1、Tab_A中的记录始终在Tab_B前边
      2、在各自的记录中,按照字段time排序
      3、如果两张表中有ID相同的,仅保留Tab_A中的记录

请不吝赐教,定高分感谢!
------解决方案--------------------
试试这个:

select id,time,other
from 
(
select *,1 as v from Tab_A

union all

select *,2 as v from Tab_B 
where not exists(select 1 from Tab_A where Tab_A.id = Tab_B.id)
)t
order by v,time

------解决方案--------------------

create table Tab_A (id int,[time] datetime,other nvarchar(10))
insert into Tab_A
select 1,'2013-01-01','A' union all
select 2,'2013-01-02','B' union all
select 3,'2013-01-03','C' union all
select 4,'2013-01-04','D'
create table Tab_B (id int,[time] datetime,other nvarchar(10))
insert into Tab_B
select 2,'2013-01-06','B' union all
select 4,'2013-01-04','C' union all
select 5,'2013-01-01','D'

select *,'A' from Tab_A 
UNION ALL
select *,'B' from Tab_B where Tab_B.id not in(select id from Tab_A) order by time 
/*
1 2013-01-01 00:00:00.000 A A
2 2013-01-02 00:00:00.000 B A
3 2013-01-03 00:00:00.000 C A
4 2013-01-04 00:00:00.000 D A
5 2013-01-08 00:00:00.000 D B
*/

------解决方案--------------------

create table Tab_A (id int,[time] datetime,other nvarchar(10))
insert into Tab_A
select 1,'2013-01-01','A' union all
select 2,'2013-01-02','B' union all
select 3,'2013-01-03','C' union all
select 4,'2013-01-04','D'
create table Tab_B (id int,[time] datetime,other nvarchar(10))
insert into Tab_B
select 2,'2013-01-06','B' union all
select 4,'2013-01-04','C' union all
select 5,'2013-01-01','D'


select *,'A' AS 表 from Tab_A 
UNION ALL
select *,'B' from Tab_B where Tab_B.id not in(select id from Tab_A) order by 表,time 
/*
1 2013-01-01 00:00:00.000 A A
2 2013-01-02 00:00:00.000 B A
3 2013-01-03 00:00:00.000 C A
4 2013-01-04 00:00:00.000 D A
5 2013-01-01 00:00:00.000 D B
*/