高分求SQL语句
现有三个表如下:
表1: Id State Datetime
1. 已结 2007-08-13
2. 未结 2007-08-14
3. 已结 2007-08-12
表2: Id State Datetime
4. 未结 2007-08-11
5. 未结 2007-08-17
6. 已结 2007-08-16
.. .. ..
表3: Id State Datetime
7. 未结 2007-08-19
8. 未结 2007-08-20
9. 已结 2007-08-15
10. .. ..
如何用SQL语句将3个表中的所有记录合并到一起,并按照日期字段排序?(要求使用AdoQuery方式)
例: Id State Datetime
4. 未结 2007-08-11
3. 已结 2007-08-12
1. 已结 2007-08-13
2. 未结 2007-08-14
9. 已结 2007-08-15
6. 已结 2007-08-16
5. 未结 2007-08-17
7. 未结 2007-08-19
8. 未结 2007-08-20
10. .. ..
[解决办法]
--t1
Create table t1(id int,state varchar(10),rq smalldatetime)
insert t1 select 1,'已结','2007-08-13'
union all select 2,'未结','2007-08-14'
union all select 3,'已结','2007-08-12'
--t2
Create table t2(id int,state varchar(10),rq smalldatetime)
insert t1 select 4,'未结','2007-08-11'
union all select 5,'未结','2007-08-17'
union all select 6,'已结','2007-08-16'
--t3
Create table t3(id int,state varchar(10),rq smalldatetime)
insert t3 select 7,'未结','2007-08-19'
union all select 8,'未结','2007-08-20'
union all select 9,'已结','2007-08-15'
--create view
go
Create view t4
as
select * from (
select * from t1
union all
select * from t2
union all
select * from t3) A
--select t4
select * from t4
order by t4.rq
[解决办法]
select aa.ID,aa.State,aa.Datetime from (select * from 表1
union all select * from 表2
union all select * from 表3) aa Order by aa.datetime