TableA
id dtchk
1001 3/31/2018
1002 9/30/2018
1004 3/31/2019
1003 5/25/2018
1005 9/30/2019
1006 3/31/2020
TableB
id type startdate endate name
1001 1 4/5/2018 12/31/2025 akshi
1002 100 4/27/2015 12/31/2023 polard
1004 100 4/1/2017 12/31/2019 kathi
1003 1 1/25/2018 5/25/2019 smoth
1005 1 3/21/2017 12/31/2020 sumi
1005 100 3/26/2019 12/31/2021 chechi
1006 1 2/28/2019 3/31/2021 paul
1006 100 2/28/2017 3/31/2019 rand
First we need to verify dtchk is between startdate and endate based on id if date eists between those dates then we need check the types if types 1 & 100 both fits then pick row with type 100 else pick as is if the date fits in those dates
output
id name
1002 polard
1004 kathi
1003 smoth
1005 chechi
1006 paul
I think you want apply
:
select a.*, b.*
from a cross apply
(select top (1) with ties b.*
from b
where b.id = a.id and
a.dtchk between b.startdate and b.endate and
b.type in (1, 100)
order by b.type desc
) b;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.