还包括此表中与 SQL 中另一个表上的条件匹配的记录



>我在以下行中有表格:

一个:

id   param_1   param_2    status     dateUpdated
-----------------------------------------------
1    valuea   valueb    Active      2018-10-02
2    valuec   valued    Inactive    2018-09-03
3    valuee   valuef    Active      2018-10-01
4    valueg   valueh    Active      2017-01-20
5    value1   value2    Active      2018-03-03
6    value3   value4    Active      2016-10-21
...

乙:

id    a_id   some_param    dateModified
-------------------------------------
1     3      x             2018-10-04 
2     2      y             2018-06-30
3     4      aa            2018-10-01
...
99    6      ab            2018-01-16
100   3      z             2018-04-08

我希望A中的记录在特定日期之后更新,但也包括与另一个表B中的日期条件匹配的其他记录(如果尚不存在,否则返回最新日期(。

如果只有表A

select id,
param_1, 
param_2, 
dateUpdated
from A
where status = 'Active'
and dateUpdated between @someDate and @someAnotherDate

现在加入:

select distinct  A.id,
A.param_1, 
A.param_2, 
A.dateUpdated -- or B.dateModified, whichever is latest if that's even possible
from A
join B on B.a_id = A.id
where A.status = 'Active'
and ((A.dateUpdated between @someDate and @someAnotherDate) || (B.dateModified between @someDate and @someAnotherDate))

所以从上面,说someDate = '2018-10-01'someAnotherDate = '2018-10-04'我会得到:

id,  param_1   param_2    dateUpdated
------------------------------------
1    valuea   valueb      2018-10-02
3    valuee   valuef      2018-10-04
4    valueg   valueh      2018-10-01

B您想要每个a_id给定范围内的最大日期。外部联接此结果以A并使用CASE WHEN获取较新的日期。

select
a.id,
a.param_1,
a.param_2,
a.status,
case when bmax.max_date > a.dateUpdated then bmax.max_date else a.dateUpdated as updated
from a
left join
(
select a_id, max(dateModified) as max_date
from b
where dateModified between @someDate and @someAnotherDate
group by a_id
) bmax on bmax.a_id = a.id
where a.status = 'Active'
and 
(
a.dateUpdated between @someDate and @someAnotherDate
or
bmax.dateModified between @someDate and @someAnotherDate
)
order by a.id;

使用左连接和大小写表达式获取最新日期

select distinct  A.id,
A.param_1, 
A.param_2, 
case when A.dateUpdated > B.dateUpdated
then A.dateUpdated else B.dateUpdated end
from A
left join B on B.a_id = A.id
where A.status = 'Active'
and ((A.dateUpdated between @someDate and @someAnotherDate) 
OR (B.dateModified between @someDate and @someAnotherDate))

最新更新