我目前正在try 将Left join
和window
函数(例如partition by class_id order by date_to desc
)结合起来,以解决SQL中的以下问题.这是一个相当困难的问题,因为有一堆棘手的约束在起作用,对我来说,我似乎需要有一种方法来处理partitioned个子表中的哪些行(在应用windows
函数之后).
Problem.给定具有两个公共字段class_id
和prop_id
的两个表A和B,我们的目标是对于given个参数year
和month
(例如,2022-05),查询将包括来自表A的列class_id
中的all个值,当基于表B的date_to
和date_from
列的值满足某些条件时,改变同一表中的相应值prop_id
.条件是:如果表B中的相同值prop_id
在给定参数year
和month
之间具有date_from
和date_to
,则我们针对该特定class_id
将表A中的prop_id
设置为Null
.请注意,表B中的特定class_id
可能具有multiple prop_id,
,因此我们需要确定包含给定参数year
和month
的准确的date_from
和date_to
对.
样本输入
Table A
class_id prop_id
12 aa_13
13 ab_21
22 ac_11
53 bb_32
48 ac_57
Table B
class_id prop_id date_from date_to
12 aa_13 2022-02-15 2022-12-10
12 aa_31 2021-09-30 2022-02-12
13 ac_12 2021-05-18 2022-02-05
22 ac_11 2022-05-12 2022-08-25
22 ac_12 2022-01-05 2022-04-23
22 ac_13 2021-08-18 2021-11-16
53 bb_32 2022-02-06 2022-03-19
53 bb_31 2021-05-08 2022-02-05
48 ac_57 2022-02-03 2022-05-07
现在,如果给定year = 2022
和month = 5
,则预期输出为
Table A
class_id prop_id (modified properly)
12 aa_13
13 NULL -- 2022-05 > date_to = 2022-02-05
22 NULL -- 2022-05 could be between 2022-04-23 and 2022-05-11, which is outside the range between 2022-05-12 and 2022-08-25 => NULL is chosen here
53 NULL -- Same reasoning as for class_id = 22
48 NULL - 2022-05 could be beyond 2022-05-07 => set it to NULL.
Question.如何编写查询以实现上述预期输出?