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

查询两个表中日期最大的那个表中的数据
比如说
A表中有id,name,createdata
B表中有id,name,createdata

哪个表中的日期最大,然后查询哪个表中的所有数据,。

------解决方案--------------------
SQL code

;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)

------解决方案--------------------
with cte as(
select *,'a' tn from a
union all
select *,'b' tn from b

select id,name,createdata 
from cte as t 
where tn=(select top 1 tn from cte where createdata=(select max(createdata) from cte) )
------解决方案--------------------
SQL code
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
*/

------解决方案--------------------
你是说那个表的 createdate 最大,就取那个表的

SQL code
if (select max(createdate ) from a)>(select max(createdate ) from b)
select * from a
else 
select * from b