I have a report which uses a dozen of CTEs and takes awfuly long to execute. Thing is that a lot of those CTEs use the same tables, joined in the same way, but on different conditions, depending on the column:
WITH
Kps_CTE (sp_id,ksd_ma_s) As
(
select wir_sp_id,SUM(ksd_ma)
from ksd
inner join ks on ksd_ks_id=ks_id
inner join do ON ksd_do_id=do_id AND do_dot_id in (101)
inner join wi ON do_wi_id=wi_id
inner join wir ON wir_wi_id=wi_id
INNER JOIN sp ON wir_sp_id=sp_id
where ksd_ksk_id=13
AND sp_date >= '2013-01-01'
group by wir_sp_id
),
Kis_CTE (sp_id,ksd_wn_s) As
(
select wir_sp_id,SUM(ksd_wn)
from ksd
inner join ks on ksd_ks_id=ks_id
inner join do ON ksd_do_id=do_id AND do_dot_id in (4)
inner join wi ON do_wi_id=wi_id
inner join wir ON wir_wi_id=wi_id
INNER JOIN sp ON wir_sp_id=sp_id
where ksd_ksk_id=14
AND sp_date>= '2013-01-01'
group by wir_sp_id
)
select * from ...
So right now I get only two columns per each table. I would like to avoid joining the same tables all over again and create a few columns in one CTE using different conditions. Is this possible? If I just join these two I won't save much resources.