日期:2014-05-17 浏览次数:20434 次
;with cte as(
select * from a
union all
select * from b
)
select * from cte as t
where createdata=(select max(createdata) from cte where name=t.name)
if object_id('TabA') is not null drop table TabA
go
create table TabA(id int,name int,createdate datetime)
go
insert into TabA
select 1,111,'2012-08-01' union all
select 2,222,'2012-08-12' union all
select 3,333,'2012-08-03'
go
if object_id('TabB') is not null drop table TabB
go
create table TabB(id int,name int,createdate datetime)
go
insert into TabB
select 1,111,'2012-08-09' union all
select 2,222,'2012-08-02' union all
select 3,333,'2012-08-13'
go
;with t as
(
select *,(select max(createdate) from TabA) flag from TabA
union all
select *,(select max(createdate) from TabB) flag from TabB
)
select id,name,createdate from t
where t.flag=(select max(flag) from t)
/*
id name createdate
----------- ----------- -----------------------
2 222 2012-08-12 00:00:00.000
1 111 2012-08-09 00:00:00.000
3 333 2012-08-13 00:00:00.000
*/
if (select max(createdate ) from a)>(select max(createdate ) from b)
select * from a
else
select * from b