PSQL - query to determin if a defined interval is matched
I have a PSQL DB with two tables, "months" and "obligations"
"obligations.start_month" is foreign key´d to "months.id"
months
======
id alias
-- -----
1 01.2021
2 02.2021
3 03.2021
4 04.2021
5 05.2021
6 06.2021
obligations
===========
id alias start_month interval_months
-- ----- ----------- ---------------
1 one 1 1
2 two 1 2
3 three 3 3
I am looking for the SQL question to the answer which obligation falls within the asked for month.
This is my best attempt yet, n being replaceable:
select *
from obligations
where
start_month <= 3
and start_month + (n*interval_months) = 3
Most likely the last line of my query anyways needs to be rewritten, but I am lacking ideas of how. I want to have all the rows, that are either in the start_month or fit into the interval. If asking for month 3, it should return obligation 1(occuring every month) and 2(starting in month 1 + every other month , so in 3, 5, 7, and so on) and obligation 3(starting in month 3). The data is not explicitely stating that, so i need to calculate , based on the start month + n-times the interval and looking if it matches. Basically, for the scenario sketched above, it should return like that:
month obligations_matching
---- --------------------
1 one
two
2 one
3 one
two
three
4 one
5 one
two
6 one
three
I am fiddling with things like "generate_series" to allow multiple calculation operations for the different interval scenarios but can not seem to wrap my head around it well enough. I can find the interval MANUALLY by KNOWING the multiplier, but can not automate this process.
Any input how to handle the variable multiplicator(1*interval_months)?
Kind regards Martin
from Recent Questions - Stack Overflow https://ift.tt/3zq69Lj
https://ift.tt/eA8V8J
Comments
Post a Comment