客户表Account,字段modifiedOn,修改时间
拜访记录表Activity,字段createdOn,创建时间,和客户表有accountId=accountId关联
现在要查询关于这个客户表中,拜访记录时间或者修改时间两个时间中最近的一个时间小于当前时间减掉45天的客户记录,可能我表达的不是很清楚,
例子
客户表 Account
AccountId modifiedOn
1 2013-03-04
2 2014-02-02
3 2013-11-24
4 2013-11-11
拜访记录表 Activity
accountId createdOn
1 2014-02-01
2 2013-11-11
3 2013-12-01
4 2013-12-11
4 2014-02-20
查询出来应该是只有accoutId=3的记录符合条件
------解决方案--------------------
这样吗:
create table Account(AccountId int,modifiedOn datetime)
insert into Account
select 1 ,'2013-03-04' union all
select 2 ,'2014-02-02' union all
select 3 ,'2013-11-24'
create table Activity(accountId int,createdOn datetime)
insert into Activity
select 1 ,'2014-02-01' union all
select 2 ,'2013-11-11' union all
select 3 ,'2013-12-01'
go
select *
from
(
select accountId,MAX(modifiedOn) as date
from
(
select * from ACCOUNT
union all
select * from Activity
)t
group by accountId
)t
where date <= datediff(day,45,getdate())