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

查询两个表中日期最大的那个表中的数据,该怎么处理

2012-08-27 
查询两个表中日期最大的那个表中的数据比如说A表中有id,name,createdataB表中有id,name,createdata哪个表

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

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

[解决办法]

SQL code
;with cte  as(select * from aunion allselect * 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 TabAgocreate table TabA(id int,name int,createdate datetime)goinsert into TabAselect 1,111,'2012-08-01' union allselect 2,222,'2012-08-12' union allselect 3,333,'2012-08-03'goif object_id('TabB') is not null drop table TabBgocreate table TabB(id int,name int,createdate datetime)goinsert into TabBselect 1,111,'2012-08-09' union allselect 2,222,'2012-08-02' union allselect 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 twhere t.flag=(select max(flag) from t)/*id          name        createdate----------- ----------- -----------------------2           222         2012-08-12 00:00:00.0001           111         2012-08-09 00:00:00.0003           333         2012-08-13 00:00:00.000*/
[解决办法]
你是说那个表的 createdate 最大,就取那个表的

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

热点排行