I have a table with tax rates. Each tax rate has two date fields: ‘valid_from’ and ‘valid_to’. ‘valid_to’ can be NULL, then the tax rate is valid until a later tax rate is inserted. Now I want to determine all tax rates valid in a given period with :start_date and :end_date. The problem is that a tax rate without ‘valid_to’ is valid, viewed individually, as long as its valid_from is not after the given period. So I have to take into account whether such tax rates have been replaced by later tax rates. But it can also be the case that a tax rate with valid_to = NULL falls in part of the given period and then a new tax rate takes over the next part of the period.
My approach still has problems with this:
SELECT *
FROM taxes t1
WHERE
t1.valid_from <= :end_date
AND (t1.valid_to >= :start_date OR t1.valid_to IS NULL)
AND NOT EXISTS (
SELECT 1
FROM taxes t2
WHERE t2.valid_from > t1.valid_from
AND t2.valid_from <= :end_date
AND (t2.valid_to IS NULL OR t2.valid_to > :start_date)
AND t2.valid_from <= IFNULL(t1.valid_to, :end_date)
);