У меня есть этот уродливый запрос ....
sum(CASE
WHEN effective_from_date < '2011-05-24' THEN (rate * (effective_to_date - '2011-05-24' + 1))
WHEN effective_to_date > '2011-05-28' THEN (rate * ('2011-05-28' - effective_from_date + 1))
ELSE (rate * (effective_to_date - effective_from_date + 1))
END
) as price_cal_rate
FROM calendar_event
WHERE property_rid = (SELECT rid FROM property WHERE web_id = 'T28314') AND
((effective_from_date BETWEEN '2011-05-24' AND '2011-05-28') OR (effective_to_date BETWEEN '2011-05-24' AND '2011-05-28'))
AND
NOT EXISTS (
SELECT days_diff FROM (
SELECT ((effective_from_date - lag(effective_to_date) OVER (PARTITION BY NULL ORDER BY effective_from_date ASC))) AS days_diff, effective_from_date, effective_to_date
FROM calendar_event
WHERE property_rid = (SELECT rid FROM property WHERE web_id = 'T28314') AND
((effective_from_date BETWEEN '2011-05-26' AND '2011-05-28') OR (effective_to_date BETWEEN '2011-05-26' AND '2011-05-28'))
) AS t WHERE COALESCE(days_diff, 0) > 1
) AND EXISTS (select * from (
select min(effective_from_date) as min_date, max(effective_to_date) as max_date FROM calendar_event
WHERE property_rid = (SELECT rid FROM property WHERE web_id = 'T28314') AND
((effective_from_date BETWEEN '2011-05-24' AND '2011-05-28') OR (effective_to_date BETWEEN '2011-05-24' AND '2011-05-28'))
) as max_min WHERE min_date <= '2011-05-24' and max_date >= '2011-05-28')
запрос вычисляет коэффициент за диапазон дат .... запрос в порядке ... но в нем много дублированиязапрос .... Мне было интересно, есть ли хороший способ сохранить результат этого подзапроса где-нибудь
FROM calendar_event
WHERE property_rid = (SELECT rid FROM property WHERE web_id = 'T28314')
AND
((effective_from_date BETWEEN '2011-05-24' AND '2011-05-28') OR (effective_to_date BETWEEN '2011-05-24' AND '2011-05-28'))
и использовать его в моем запросе ....