Skip to content
Advertisement

Modifying records in one column of a table conditioning on the date ranges in the other table

I am currently trying to combine Left join with window function (e.g. partition by class_id order by date_to desc) to solve the following problem in SQL. It is quite a difficult problem due to a bunch of tricky constraints that come into play, and it seems to me I need to have a way to choose which rows from the partitioned sub-tables (after applying windows function) to go with.

Problem. Given two tables A and B having two common fields class_id and prop_id, our goal is that for given parameters year and month (e.g. 2022-05), the query would include all values in the column class_id from Table A, change the corresponding value prop_id in the same table when certain conditions are satisfied based on the values of date_to and date_from columns of Table B. The conditions are: if the same value prop_id in Table B has date_from and date_to between the given parameters year and month, then we set the prop_id in Table A to Null for that particular class_id. Note that a specific class_id in Table B might have multiple prop_id, so we need to determine the exact pair of date_from and date_to that contains the given parameters year and month.

Sample Inputs

Now, if given year = 2022 and month = 5, then the expected output is

Question. How can I write a query to achieve the above expected output?

Advertisement

Answer

You didn’t provide a tag for the DB engine, so first is for Postgres, and then Snowflake as per your comment.

Postgres:

class_id | prop_id | modified_prop_id
-------: | :------ | :---------------
      12 | aa_13   | aa_13           
      22 | ac_11   | null            
      13 | ac_21   | null            
      48 | ac_57   | null            
      53 | bb_32   | null            

db<>fiddle here

Snowflake:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement