WITH cte_pens_product AS
(
SELECT
products.id,
products."name"
FROM ourpension.contract_product_history_history history
JOIN prod_line.pens_product products
ON products.id = history.pens_product_id
WHERE history.contract_id = 13063250
AND CURRENT_TIMESTAMP BETWEEN
history.begin_date
AND COALESCE(history.end_date, 'infinity')
LIMIT 1
)
SELECT
cpp.id AS product_id,
cpp."name" AS product_name,
ppf.type_group_form_id,
tgf.doc_type,
lf.id AS landscape_form_id,
lf.code,
lf.start_date,
lf.end_date,
lf.filename
FROM cte_pens_product cpp
LEFT JOIN prod_line.pens_product_hb_print_form ppf
ON ppf.pens_product_id = cpp.id
LEFT JOIN ourpension.type_group_form tgf
ON tgf.id = ppf.type_group_form_id
LEFT JOIN ourpension.landscape_form lf
ON lf.type_group_form_id = ppf.type_group_form_id
ORDER BY
ppf.type_group_form_id,
lf.start_date DESC;