sql—验证日期之间是否存在日期,并根据类型选择特定行

vd2z7a6w  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(290)

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

表B

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

首先,我们需要根据id验证dtchk是否在startdate和endate之间如果日期在这两个日期之间,那么我们需要检查类型如果类型1和100都匹配,那么用类型100选择行,否则就按原样选择日期是否匹配这些日期
输出

id      name
1002    polard
1004    kathi
1003    smoth
1005    chechi
1006    paul
jtjikinw

jtjikinw1#

我想你想要 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;

相关问题