How to optimize left join subqueries in oracle - optimization

I would like to optimize a query with so many left join sub queries.See my query;
SELECT DISTINCT pi.proforma_no,
m.vv_cd,
m.pid,
bl.bill_lading_nbr,
bld.cntr_nbr,
NVL(ts.quantity, bld.quantity) AS quantity,
vsc.vsl_nm,
vsc.in_voy_nbr,
m.rec_status,
bld.idx_no,
bld.colli_type,
bld.volume,
bld.gross_weight_kgs,
bld.has_heavy_lift,
NVL(NVL(pi.fa,pi.consignee),NVL(bld.cust_tariff_client,NVL(bl.fa,bl.consignee))) AS client,
col.is_pos,
col.cargo_type,
bld.direct_delivery,
cn.cntr_seq_nbr,
bld.package_type_cd,
bld.cargo_dtl_desc,
NVL(ts.quantity, bld.quantity) AS quantity,
bld.weight,
bld.t1,
bl.pload AS port_code,
bld.purpose,
bld.volume,
bld.GROSS_WEIGHT_KGS,
pi.WAIVE_DOC_FEE,
pi.WAIVE_DOC_FEE_REMARKS,
m.pid
|| '='
|| trim(bl.bill_lading_nbr)
|| '='
|| bld.idx_no
|| '='
|| trim(bld.cntr_nbr) AS unique_key,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',DECODE(tariff.is_metric_ton,'Y',tariff.local_rate *bld.weight,tariff.local_rate*bld.quantity), NVL(DECODE(ext_tariff_toStd.is_metric_ton,'Y',ext_tariff_toStd.local_rate*bld.weight,ext_tariff_toStd.local_rate*bld.quantity),0)), DECODE('N','N',DECODE(custTar.is_metric_ton,'Y',custTar.local_rate*bld.weight,custTar.local_rate*bld.quantity),0)) AS local_rate,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',DECODE(tariff.is_metric_ton,'Y',tariff.global_rate *bld.weight,tariff.global_rate*bld.quantity), NVL(DECODE(ext_tariff_toStd.is_metric_ton,'Y',ext_tariff_toStd.global_rate*bld.weight,ext_tariff_toStd.global_rate*bld.quantity),0)), DECODE('N','N',DECODE(custTar.is_metric_ton,'Y',custTar.global_rate*bld.weight,custTar.global_rate*bld.quantity),0)) AS global_rate,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',tariff.version_nbr,DECODE(col.tariff_ext_cost_id,NULL,0,NVL(ext_tariff_toStd.version_nbr,NVL(ext_tariff.version_nbr,tariff.version_nbr)))), -1) AS version_nbr,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',tariff.id,DECODE(col.tariff_ext_cost_id,NULL,0,NVL(ext_tariff_toStd.id,NVL(ext_tariff.id,tariff.id)))), -1) AS tariff_id,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',0,(NVL(DECODE(ext_tariff.is_metric_ton,'Y',ext_tariff.local_rate *bld.weight,ext_tariff.local_rate*bld.quantity),0))), 0) AS local_ext_amount,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',0,(NVL(DECODE(ext_tariff.is_metric_ton,'Y',ext_tariff.global_rate *bld.weight,ext_tariff.global_rate*bld.quantity),0))), 0) AS global_ext_amount,
(NVL(ts.quantity, bld.quantity) *NVL(disch.local_amount,0)) + DECODE(col.is_pos,'Y',DECODE(NVL(pos.local_amount,0),0,0,(bld.weight*pos.local_amount)),0) + DECODE(col.is_pos_add_rate,'Y',DECODE(bld.weight,0,0,NVL(addPos.local_amount,0)),0) AS local_other_amount,
(NVL(ts.quantity, bld.quantity) *NVL(disch.global_amount,0)) + DECODE(col.is_pos,'Y',DECODE(NVL(pos.global_amount,0),0,0,(bld.weight*pos.global_amount)),0) + DECODE(col.is_pos_add_rate,'Y',DECODE(bld.weight,0,0,NVL(addPos.global_amount,0)),0) AS global_other_amount,
NVL(doc.local_amount,0) + (DECODE(SIGN(ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.local_amount,0),2)-ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.local_amount,0),0)-0.05),-1, ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.local_amount,0),0)+0.05, ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.local_amount,0),0))) AS local_doc_amount,
NVL(doc.global_amount,0) + (DECODE(SIGN(ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.global_amount,0),2)-ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.global_amount,0),0)-0.05),-1, ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.global_amount,0),0)+0.05, ROUND(ROUND(to_number(spTax.param_value)/100,2)*NVL(doc.global_amount,0),0))) AS global_doc_amount,
(NVL(ts.quantity, bld.quantity) *NVL(disch.local_amount,0)) AS local_disch_amount,
DECODE(col.is_pos,'Y',DECODE(NVL(pos.local_amount,0),0,0,(bld.weight *pos.local_amount)),0) + DECODE(col.is_pos_add_rate,'Y',DECODE(bld.weight,0,0,NVL(addPos.local_amount,0)),0) AS local_pos_amount,
(NVL(ts.quantity, bld.quantity) *NVL(disch.global_amount,0)) AS global_disch_amount,
DECODE(col.is_pos,'Y',DECODE(NVL(pos.global_amount,0),0,0,(bld.weight *pos.global_amount)),0) + DECODE(col.is_pos_add_rate,'Y',DECODE(bld.weight,0,0,NVL(addPos.global_amount,0)),0) AS global_pos_amount,
NVL(doc.local_amount,0) AS local_pure_doc_amount,
NVL(doc.global_amount,0) AS global_pure_doc_amount,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',tariff.local_rate, NVL(ext_tariff_toStd.local_rate,0)), DECODE('N','N',custTar.local_rate,0)) AS tariff_local_rate,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'', DECODE('N','N',tariff.global_rate, NVL(ext_tariff_toStd.global_rate,0)), DECODE('N','N',custTar.global_rate,0)) AS tariff_global_rate,
DECODE(pi.proforma_no, NULL, 'N', DECODE(bld.is_paid,'N',DECODE(pi.proforma_no,NULL,'N',DECODE(pi.is_special,'Y','SP','UP')),bld.is_paid)) AS bld_status,
tariff.remark,
col.is_std_cargo,
DECODE(NVL(bld.CUST_TARIFF_CLIENT,''),'',DECODE('N','N',tariff.serv_id
||NVL(ext_tariff_toStd.serv_id,''),ext_tariff.serv_id),custTar.serv_id) AS serv_id
FROM manifest m
INNER JOIN vessel_call vsc
ON vsc.vv_cd = m.vv_cd
LEFT JOIN vessel_event ve
ON ve.vv_cd = vsc.vv_cd
INNER JOIN bl
ON bl.pid = m.pid
AND bl.transfer_status = 'N'
INNER JOIN bl_dtl bld
ON bld.pid = m.pid
AND bld.is_paid = 'N'
AND bld.bill_lading_nbr = bl.bill_lading_nbr
LEFT JOIN tally_sheet ts
ON ts.manifest_pid = m.pid
AND trim(upper(ts.bill_lading_nbr)) = trim(upper(bl.bill_lading_nbr))
AND ts.cargo_idx_no = bld.idx_no
AND trim(upper(ts.cntr_nbr)) = trim(upper(bld.cntr_nbr))
INNER JOIN colli col
ON trim(col.colli_code) = trim(bld.colli_type)
LEFT JOIN
(SELECT pi.*,
pid.bill_lading_nbr,
pid.cntr_no
FROM proforma_invoice_dtl pid,
proforma_invoice pi
WHERE pid.proforma_no = pi.proforma_no
AND pi.reversal_proforma IS NULL
AND pid.quantity >= 0
AND pid.total_global_amount >=0
AND pid.reversal_proforma IS NULL
) pi
ON pi.bill_lading_nbr = bld.bill_lading_nbr
AND pi.cntr_no = bld.cntr_nbr
AND pi.vv_cd = m.vv_cd
LEFT JOIN system_parameter spTax
ON spTax.param_cd = 'SAF_VAT'
LEFT JOIN
(SELECT NVL(serv.local_amount,0) AS local_rate,
NVL(serv.global_amount,0) AS global_rate,
tar.id,
tar.is_metric_ton,
tar.version_nbr,
tver.eff_start_dttm,
tar.remark,
serv.id AS serv_id
FROM tariffs tar
INNER JOIN tariff_details tardet
ON tardet.tariff_id = tar.id
INNER JOIN services serv
ON serv.id = tardet.service_id
INNER JOIN tariff_version tver
ON tver.version_nbr = tar.version_nbr
AND serv.service_type NOT IN ('C','R','L','D','DG')
AND serv.rec_status = 'A'
WHERE tar.rec_status = 'A'
ORDER BY tver.eff_start_dttm DESC
) tariff ON tariff.id = tariff_end_date(NVL(ve.atb,vsc.vsl_eta_dttm),DECODE(bld.purpose,'TS1W',col.TARIFF_1WAYTRANS_ID,'TS2W',col.TARIFF_2WAYTRANS_ID,col.tariff_dischg_id))
LEFT JOIN
(SELECT NVL(serv.local_amount,0) AS local_rate,
NVL(serv.global_amount,0) AS global_rate,
tar.id,
tar.is_metric_ton,
tar.version_nbr,
tver.eff_start_dttm,
serv.id AS serv_id
FROM tariffs tar
INNER JOIN tariff_details tardet
ON tardet.tariff_id = tar.id
INNER JOIN tariff_version tver
ON tver.version_nbr = tar.version_nbr
INNER JOIN services serv
ON serv.id = tardet.service_id
AND serv.service_type NOT IN ('C','R','L','D','DG')
AND serv.rec_status = 'A'
WHERE tar.rec_status = 'A'
ORDER BY tver.eff_start_dttm DESC
) ext_tariff_toStd ON ext_tariff_toStd.id = col.tariff_ext_cost_id
LEFT JOIN
(SELECT NVL(serv.local_amount,0) AS local_rate,
NVL(serv.global_amount,0) AS global_rate,
tar.id,
tar.is_metric_ton,
tar.version_nbr,
tver.eff_start_dttm,
serv.id AS serv_id,
tardet.usage
FROM tariffs tar
INNER JOIN tariff_details tardet
ON tardet.tariff_id = tar.id
INNER JOIN tariff_version tver
ON tver.version_nbr = tar.version_nbr
INNER JOIN services serv
ON serv.id = tardet.service_id
AND serv.service_type IN ('C','R','L','DG')
AND serv.rec_status = 'A'
WHERE tar.rec_status = 'A'
ORDER BY tver.eff_start_dttm DESC
) ext_tariff ON ((ext_tariff.id = col.tariff_ext_cost_id
AND NVL(ext_tariff.usage,'%') LIKE '%'
||bld.purpose
||'%')
OR ext_tariff.id = tariff_end_date(NVL(ve.atb,vsc.vsl_eta_dttm),DECODE(bld.purpose,'TS1W',col.TARIFF_1WAYTRANS_ID,'TS2W',col.TARIFF_2WAYTRANS_ID,col.tariff_dischg_id)))
LEFT JOIN
(SELECT custTar.EFFECTIVE_DTTM,
bld.bill_lading_nbr,
bld.cntr_nbr,
DECODE(NVL(DECODE(bld.purpose,'TS2W',custTar.tariff_2waytrans_amt,'TS1W',custTar.tariff_1waytrans_amt,custTar.tariff_disch_amt),0),0,local_rate,DECODE(bld.purpose,'TS2W',custTar.tariff_2waytrans_amt,'TS1W',custTar.tariff_1waytrans_amt,custTar.tariff_disch_amt)) AS local_rate,
DECODE(NVL(DECODE(bld.purpose,'TS2W',custTar.tariff_2waytrans_amt,'TS1W',custTar.tariff_1waytrans_amt,custTar.tariff_disch_amt),0),0,global_rate,DECODE(bld.purpose,'TS2W',custTar.tariff_2waytrans_amt,'TS1W',custTar.tariff_1waytrans_amt,custTar.tariff_disch_amt)) AS global_rate,
custTar.id,
DECODE(bld.purpose,'TS2W',NVL(custTar.tariff_2waytrans_mton,is_metric_ton), 'TS1W',NVL(custTar.tariff_1waytrans_mton,is_metric_ton), NVL(custTar.tariff_disch_mton,is_metric_ton)) AS is_metric_ton,
version_nbr,
cust_tariff_val.serv_id
FROM customized_tariff custTar
INNER JOIN vessel_call vsc
ON upper(vsc.vsl_nm) LIKE '%'
|| trim(upper(NVL('EURPCARGO VENEZIA','')))
|| '%'
AND vsc.in_voy_nbr = trim(upper(NVL('14120502','')))
OR vsc.vv_cd = trim(NVL('2014000433',''))
INNER JOIN manifest m
ON m.vv_cd = NVL(vsc.vv_cd,'')
INNER JOIN bl_dtl bld
ON bld.cust_tariff_client = custTar.client_code
AND bld.pid = m.pid
INNER JOIN customized_tariff_dtl custTarDtl
ON custTarDtl.cust_tar_id = custTar.id
AND trim(custTarDtl.colli_code) = bld.colli_type
LEFT JOIN
(SELECT NVL(serv.local_amount,0) AS local_rate,
NVL(serv.global_amount,0) AS global_rate,
tar.id,
tar.is_metric_ton,
tar.version_nbr,
tver.eff_start_dttm,
serv.id AS serv_id
FROM tariffs tar
INNER JOIN tariff_details tardet
ON tardet.tariff_id = tar.id
INNER JOIN tariff_version tver
ON tver.version_nbr = tar.version_nbr
INNER JOIN services serv
ON serv.id = tardet.service_id
AND serv.rec_status = 'A'
WHERE tar.rec_status = 'A'
ORDER BY tver.eff_start_dttm DESC
) cust_tariff_val ON cust_tariff_val.id = DECODE(bld.purpose,'TS2W',custTar.TARIFF_2WAYTRANS_ID,'TS1W',custTar.TARIFF_1WAYTRANS_ID,custTar.TARIFF_DISCH_ID)
WHERE trim(custTar.client_code) = bld.cust_tariff_client
AND custTar.rec_status = 'A'
ORDER BY custTar.effective_dttm DESC,
custTar.LAST_MODIFY_DTTM DESC
) custTar ON TO_CHAR(custTar.EFFECTIVE_DTTM,'yyyymmdd') <= TO_CHAR(NVL(ve.atb,vsc.vsl_eta_dttm),'yyyymmdd')
AND custTar.bill_lading_nbr = bld.bill_lading_nbr
AND custTar.cntr_nbr = bld.cntr_nbr
LEFT JOIN
(SELECT NVL(serv.local_amount,0) AS local_amount,
NVL(serv.global_amount,0) AS global_amount,
tar.id,
tar.is_metric_ton,
tar.version_nbr,
tver.eff_start_dttm
FROM tariffs tar
INNER JOIN tariff_details tardet
ON tardet.tariff_id = tar.id
INNER JOIN tariff_version tver
ON tver.version_nbr = tar.version_nbr
INNER JOIN services serv
ON serv.id = tardet.service_id
AND serv.service_type IN ('D')
AND serv.rec_status = 'A'
WHERE tar.rec_status = 'A'
ORDER BY tver.eff_start_dttm DESC
) disch ON disch.id = col.tariff_ext_cost_id
LEFT JOIN
(SELECT rownum AS seq,
local_amount,
global_amount,
last_modify_dttm
FROM services
WHERE service_type = 'U'
AND rec_status = 'A'
ORDER BY last_modify_dttm DESC
) doc
ON doc.seq = 1
LEFT JOIN
(SELECT rownum AS seq,
local_amount,
global_amount,
last_modify_dttm
FROM services
WHERE service_type = 'L'
AND rec_status = 'A'
ORDER BY last_modify_dttm DESC
) heavyLift
ON heavyLift.seq = 1
LEFT JOIN
(SELECT rownum AS seq,
local_amount,
global_amount,
last_modify_dttm
FROM services
WHERE service_type = 'P'
AND rec_status = 'A'
ORDER BY last_modify_dttm DESC
) pos
ON pos.seq = 1
LEFT JOIN
(SELECT rownum AS seq,
local_amount,
global_amount,
last_modify_dttm
FROM services
WHERE service_type = 'O'
AND rec_status = 'A'
ORDER BY last_modify_dttm DESC
) addPos
ON addPos.seq = 1
LEFT JOIN cntr cn
ON cn.cntr_nbr = bld.cntr_nbr
AND cn.txn_status = 'A'
WHERE m.pid
|| '='
|| trim(bl.bill_lading_nbr)
|| '='
|| bld.idx_no
|| '='
|| trim(bld.cntr_nbr) LIKE NVL(null,'%')
AND (m.vv_cd = trim(NVL('2014000433',''))
OR ( upper(vsc.vsl_nm) LIKE '%'
|| trim(upper(NVL('EURPCARGO VENEZIA','')))
|| '%'
AND vsc.in_voy_nbr = trim(upper(NVL('14120502',''))) ))
ORDER BY bl.bill_lading_nbr;
Any suggestion for optimizing left join sub queries for oracle.

Related

How can I optimize a query like this that is taking 17s

A tip would be welcome. I tried to create an expression index on id_contrato but it gave me only 1s of speed. The query is taking 17s. I just need some medium to small improvement . I am using Firebird 2.0.
select sum(VL_EMPENHO) as VL_EMPENHO from (select distinct
E.ID_EMPENHO || '/' || E.ID_EXERCICIO as NUM_EMPENHO,
E.DATA,
E.VALOR + coalesce((select SUM(E__.VALOR) from CONTABIL_EMPENHO E__ where E__.ID_EMPENHO = E.ID_EMPENHO and E__.NUMERO = E.NUMERO
and E__.ID_ORGAO = E.ID_ORGAO and E__.ID_EXERCICIO = E.ID_EXERCICIO
and (E.TIPO_DESPESA = 'EMO' and E__.TIPO_DESPESA = 'EOA')), 0) +
coalesce(( select sum(V.VALOR)
from CONTABIL_VARIACAO V
LEFT JOIN CONTABIL_EVENTO ev on ev.ID_FICHA = v.ID_FICHA and ev.ID_EXERCICIO = v.ID_EXERCICIO
LEFT JOIN CONTABIL_EVENTO_ITEM EI on EI.ID_EVENTO = ev.ID_EVENTO and EI.TIPO_EVENTO = ev.TIPO_EVENTO
LEFT JOIN CONTABIL_PLANO_CONTA PD ON PD.ID_REGPLANO = EI.ID_DEBITO
LEFT JOIN CONTABIL_PLANO_CONTA PC ON PC.ID_REGPLANO = EI.ID_CREDITO
where ((PD.id_plano in ( '632910100', '631990000') or PC.id_plano in ( '632910100', '631990000') ) or (PD.id_plano in ( '195920000', '195910000') or PC.id_plano in ( '195920000', '195910000') ))
AND V.ID_EMPENHO = E.ID_EMPENHO
and V.ANO = E.ID_EXERCICIO and V.ID_ORGAO = E.ID_ORGAO
), 0) as VL_EMPENHO,
(select first 1 P.DATA from CONTABIL_PAGAMENTO P
inner join CONTABIL_EMPENHO E__ on E__.ID_REGEMPENHO = P.ID_REGEMPENHO
where
(E.TIPO_DESPESA = 'EMO' and E__.TIPO_DESPESA in ('EMO', 'SEO', 'EMR', 'SER'))
and E__.ID_EXERCICIO = E.ID_EXERCICIO and E__.ID_ORGAO = E.ID_ORGAO and
E__.ID_EMPENHO = E.ID_EMPENHO and P.ANULACAO = 'N' order by P.ID_PAGTO desc) as DT_PAGTO,
(select sum(P.VALOR) from CONTABIL_PAGAMENTO P
inner join CONTABIL_EMPENHO E__ on E__.ID_REGEMPENHO = P.ID_REGEMPENHO
where
(E.TIPO_DESPESA = 'EMO' and E__.TIPO_DESPESA in ('EMO', 'SEO', 'EMR', 'SER'))
and E__.ID_EXERCICIO = E.ID_EXERCICIO and E__.ID_ORGAO = E.ID_ORGAO and
E__.ID_EMPENHO = E.ID_EMPENHO) as VL_PAGO
from CONTABIL_CONTRATO C
left join CONTABIL_EMPENHO E on substring(E.ID_CONTRATO from 1 for 8) = substring(C.ID_CONTRATO from 1 for 8) and
E.ID_ORGAO = C.ID_ORGAO and E.TIPO_DESPESA in ('EMO')
where C.ID_ORGAO = '020000' and C.ID_CONTRATO like '00072017%' and E.ID_COMPRA <> 0 order by 1, 2)
Many items that may help your query. For indexes, I would start by having the following to help optimize
table index
CONTABIL_EMPENHO ( ID_ORGAO, TIPO_DESPESA, ID_CONTRATO, ID_EMPENHO, ID_EXERCICIO )
CONTABIL_VARIACAO ( ID_ORGAO, ID_EMPENHO, ANO )
CONTABIL_PAGAMENTO ( ID_REGEMPENHO )
Your final WHERE clause includes the 'E' alias which turns your LEFT JOIN to an INNER JOIN, so I just moved the 'AND' clause to the 'E' join section. Since your outer query is doing a SUM() of the inner table results, you do not need the 'order by 1, 2' clause, so I removed that.
You join between
CONTABIL_CONTRATO C join CONTABIL_EMPENHO E
on substring( E.ID_CONTRATO from 1 for 8)
= substring( C.ID_CONTRATO from 1 for 8)
will most probably give you duplicate / false answers because you are comparing on the left 8 characters of the contractor id. So, lets take a look at the following sample data. Notice each of the IDs starts with "12345678" representing the substring from 1 for 8 of equality. This leaves the remainder of the ID that will cause false join results as you will see.
CONTABIL_CONTRATO C
ID_CONTRATO
12345678A
12345678B
12345678C
12345678D
CONTABIL_EMPENHO E
ID_CONTRATO
12345678E
12345678F
12345678G
12345678H
Without seeing actual data, this will create 16 times results via
C.ID =12345678(A) joins to E.12345678(E), E.12345678(F), E.12345678(G) and E.12345678(H)
C.ID =12345678(B) joins to E.12345678(E), E.12345678(F), E.12345678(G) and E.12345678(H)
C.ID =12345678(C) joins to E.12345678(E), E.12345678(F), E.12345678(G) and E.12345678(H)
C.ID =12345678(D) joins to E.12345678(E), E.12345678(F), E.12345678(G) and E.12345678(H)
but then you'll have the same with
(B) joined to (E) (F) (G) (H)
(C) joined to (E) (F) (G) (H)
(D) joined to (E) (F) (G) (H)
and then the inverse
(E) joined to (A) (B) (C) (D)
(F) joined to (A) (B) (C) (D)
(G) joined to (A) (B) (C) (D)
(H) joined to (A) (B) (C) (D)
So, for each instance you keep re-querying the same columns sub-selects over and over to get the same repeats of data which I think is COMPLETELY in-accurate to what you want. But not seeing actual data, can not confirm.
What you PROBABLY want is where the C.contractor ID = E.contractor ID. Your FINAL where clause that is explicitly limiting the scope to contractor like '00072017%' would limit down your results to just those contractors in question. So, I changed the JOIN to be on same matching contractor ID.
But that gets completely eliminated because you are never really using your CONTABIL_CONTRATO table except to do the join to the CONTABIL_EMPENHO. Since the two common columns are in both tables, I just changed the where clause to reference the 'E' columns to the ID_ORGAO and ID_CONTRATO values.
With each of your coalesce(), since the main where clause already has E.TIPO_DESPESA = 'EMO', it is not needed in the inner column-select query.
select
sum( PQ.VL_EMPENHO) VL_EMPENHO
from
(
select distinct
E.ID_EMPENHO || '/' || E.ID_EXERCICIO NUM_EMPENHO,
E.DATA,
E.VALOR
+ coalesce( ( select SUM(E__.VALOR)
from CONTABIL_EMPENHO E__
where
E.ID_ORGAO = E__.ID_ORGAO
and E__.TIPO_DESPESA = 'EOA'
AND E.ID_EMPENHO = E__.ID_EMPENHO
and E.NUMERO = E__.NUMERO
and E.ID_EXERCICIO = E__.ID_EXERCICIO )
, 0)
+ coalesce( ( select sum(V.VALOR)
from CONTABIL_VARIACAO V
LEFT JOIN CONTABIL_EVENTO ev
on v.ID_FICHA = ev.ID_FICHA
and v.ID_EXERCICIO = ev.ID_EXERCICIO
LEFT JOIN CONTABIL_EVENTO_ITEM EI
on ev.ID_EVENTO = EI.ID_EVENTO
and ev.TIPO_EVENTO = EI.TIPO_EVENTO
LEFT JOIN CONTABIL_PLANO_CONTA PD
ON EI.ID_DEBITO = PD.ID_REGPLANO
LEFT JOIN CONTABIL_PLANO_CONTA PC
ON EI.ID_CREDITO = PC.ID_REGPLANO
where
E.ID_ORGAO = V.ID_ORGAO
and E.ID_EMPENHO = V.ID_EMPENHO
and E.ID_EXERCICIO = V.ANO
AND (
( PD.id_plano in ( '632910100', '631990000')
or PC.id_plano in ( '632910100', '631990000')
)
or
( PD.id_plano in ( '195920000', '195910000')
or PC.id_plano in ( '195920000', '195910000')
)
)
)
, 0) as VL_EMPENHO,
( select first 1
P.DATA
from
CONTABIL_EMPENHO E__
inner join CONTABIL_PAGAMENTO P
on E__.ID_REGEMPENHO = P.ID_REGEMPENHO
AND P.ANULACAO = 'N'
where
E.ID_ORGAO = E__.ID_ORGAO
and E.ID_EMPENHO = E__.ID_EMPENHO
and E.ID_EXERCICIO = E__.ID_EXERCICIO
and E__.TIPO_DESPESA in ('EMO', 'SEO', 'EMR', 'SER')
order by
P.ID_PAGTO desc ) as DT_PAGTO,
( select
sum(P.VALOR)
from
CONTABIL_EMPENHO E__
inner join CONTABIL_PAGAMENTO P
on E__.ID_REGEMPENHO = P.ID_REGEMPENHO
where
E.ID_ORGAO = E__.ID_ORGAO
and E.ID_EMPENHO = E__.ID_EMPENHO
and E.ID_EXERCICIO = E__.ID_EXERCICIO
and E__.TIPO_DESPESA in ('EMO', 'SEO', 'EMR', 'SER') ) as VL_PAGO
from
CONTABIL_EMPENHO E
where
E.ID_ORGAO = '020000'
and E.ID_CONTRATO like '00072017%'
and E.TIPO_DESPESA in 'EMO'
and E.ID_COMPRA <> 0 ) PQ
I believe I am accurate in my assessment of your query needs. That and the indexes will perform significantly better.
In outer query you are only using column VL_EMPENHO. So I have removed all the other columns from inner query. It should be executed faster now.
select sum(VL_EMPENHO) as VL_EMPENHO from (select distinct
E.VALOR + coalesce((select SUM(E__.VALOR) from CONTABIL_EMPENHO E__ where E__.ID_EMPENHO = E.ID_EMPENHO and E__.NUMERO = E.NUMERO
and E__.ID_ORGAO = E.ID_ORGAO and E__.ID_EXERCICIO = E.ID_EXERCICIO
and (E.TIPO_DESPESA = 'EMO' and E__.TIPO_DESPESA = 'EOA')), 0) +
coalesce(( select sum(V.VALOR)
from CONTABIL_VARIACAO V
LEFT JOIN CONTABIL_EVENTO ev on ev.ID_FICHA = v.ID_FICHA and ev.ID_EXERCICIO = v.ID_EXERCICIO
LEFT JOIN CONTABIL_EVENTO_ITEM EI on EI.ID_EVENTO = ev.ID_EVENTO and EI.TIPO_EVENTO = ev.TIPO_EVENTO
LEFT JOIN CONTABIL_PLANO_CONTA PD ON PD.ID_REGPLANO = EI.ID_DEBITO
LEFT JOIN CONTABIL_PLANO_CONTA PC ON PC.ID_REGPLANO = EI.ID_CREDITO
where ((PD.id_plano in ( '632910100', '631990000') or PC.id_plano in ( '632910100', '631990000') ) or (PD.id_plano in ( '195920000', '195910000') or PC.id_plano in ( '195920000', '195910000') ))
AND V.ID_EMPENHO = E.ID_EMPENHO
and V.ANO = E.ID_EXERCICIO and V.ID_ORGAO = E.ID_ORGAO
), 0) as VL_EMPENHO
from CONTABIL_CONTRATO C
left join CONTABIL_EMPENHO E on substring(E.ID_CONTRATO from 1 for 8) = substring(C.ID_CONTRATO from 1 for 8) and
E.ID_ORGAO = C.ID_ORGAO and E.TIPO_DESPESA in ('EMO')
where C.ID_ORGAO = '020000' and C.ID_CONTRATO like '00072017%' and E.ID_COMPRA <> 0 order by 1, 2)

Getting a second query as a field in a first one

I'm fairly new to writing queries and I'm struggling with getting the next to queries combined:
SELECT od.ODCode
, c.Description as 'Line Position'
, ps.Description as 'Pallet Stacking'
, pt.Description as 'Pallet Type'
, odex.PalletRows
, odex.PalletTypeID
,CONCAT(( SELECT sp.SpecPropertyValue FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'DocDir'and sc.specclassname = 'Pallettypedoc'
),
(SELECT sp.SpecPropertyValue FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'Documentname'and sc.specclassname = 'Pallettypedoc' )) AS Spec
FROM ODExitPallet odex
INNER JOIN OperationDescr od
ON od.OperationDescrID=odex.OperationDescrID
INNER JOIN PalletStacking ps
ON ps.PalletStackingID=odex.PalletStackingID
INNER JOIN PalletType pt
ON pt.PalletTypeID=odex.PalletTypeID
INNER JOIN Code c
on c.CodeNumber=odex.LinePosition and c.CodeTypeID=72
INNER JOIN WorkOrder wo
on wo.OperationDescrID=odex.OperationDescrID
WHERE wo.WorkOrderID = #WorkOrderID
and
SELECT SUM(PlannedBatch) / SUM(NominalBlanks * Stacks) as NrOfPallets
FROM (SELECT WO.PlannedBatch, WO.NominalBlanks, ODEP.OperationDescrID, LinePosition,
Case when COUNT(*) = 0 then 1
else COUNT(*)
end as Stacks
FROM WorkOrder Wo
INNER JOIN ODExitPallet ODEX
ON WO.operationDescrID = ODEX.OperationDescrID
INNER JOIN Stacking ST
ON ST.PalletStackingID = ODEX.PalletStackingID
WHERE WO.WorkOrderID = #WorkOrderID
GROUP BY PlannedBatch, NominalBlanks, ODEX.OperationDescrID, LinePosition
) TOTAL
So I want to add the second query as a field in my first one. I've tried it with numerous thing like parentheses and stuff but I keep getting errors. Can someone enlighten me?
insert ( ) in whole second Query but make sure you second query return only 1 row
SELECT od.ODCode
, c.Description as 'Line Position'
, ps.Description as 'Pallet Stacking'
, pt.Description as 'Pallet Type'
, odex.PalletRows
, odex.PalletTypeID
,CONCAT(
(
SELECT sp.SpecPropertyValue
FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'DocDir'and sc.specclassname = 'Pallettypedoc'
)
,
(
SELECT sp.SpecPropertyValue FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'Documentname'and sc.specclassname = 'Pallettypedoc'
)
) AS Spec
,(
SELECT SUM(PlannedBatch) / SUM(NominalBlanks * Stacks)
FROM (
SELECT WO.PlannedBatch, WO.NominalBlanks, ODEP.OperationDescrID, LinePosition,
Case when COUNT(*) = 0 then 1
else COUNT(*)
end as Stacks
FROM WorkOrder Wo
INNER JOIN ODExitPallet ODEX
ON WO.operationDescrID = ODEX.OperationDescrID
INNER JOIN Stacking ST
ON ST.PalletStackingID = ODEX.PalletStackingID
WHERE WO.WorkOrderID = #WorkOrderID
GROUP BY PlannedBatch, NominalBlanks, ODEX.OperationDescrID, LinePosition
) TOTAL
) AS [NrOfPallets]
FROM ODExitPallet odex
INNER JOIN OperationDescr od ON od.OperationDescrID=odex.OperationDescrID
INNER JOIN PalletStacking ps ON ps.PalletStackingID=odex.PalletStackingID
INNER JOIN PalletType pt ON pt.PalletTypeID=odex.PalletTypeID
INNER JOIN Code c on c.CodeNumber=odex.LinePosition and c.CodeTypeID=72
INNER JOIN WorkOrder wo on wo.OperationDescrID=odex.OperationDescrID
WHERE wo.WorkOrderID = #WorkOrderID

Optimize query with sql server

I have the following query .its execution took 15 min .It is too much slowly .
Is there a way to optimize it ?
Query
SELECT
Id,Fees,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Fees ' AS FeesName
,#MonthName AS [MonthName]
INTO ##TempFeesMonthly
from
(
SELECT DISTINCT
1 as Id,sum(((CNTI_THPAYE *(CNTI_THFACT / CNTI_THPAYE)) *
(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate)t
--CREATE INDEX IDX_TempFeesMonthly ON ##TempFeesMonthly(WeekOfMonth)
--Calcul Temp Margin
UNION ALL
--INSERT INTO ##TempFeesMonthly(Id,Fees,WeekOfMonth,StartDate,EndDate,FeesName,[MonthName])
SELECT
2, sum(Fees) AS Fees ,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Margin ' AS FeesName
,#MonthName AS [MonthName]
from
(
SELECT DISTINCT
sum((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)-(CNTI_THPAYE *(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*1.453*1.21*#NumberOfDays) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate,CNTI_THPAYE,CNTI_DURHEBDO)t
GROUP BY WeekOfMonth,StartDate,EndDate

Select Last Record in SSRS report Designer 3.0

Trying to get the last/lastest record from ShipHead.Shipdate instead of all the records How do i Do last record with this query?
SELECT
OrderRel.ReqDate
,OrderHed.EntryPerson
,ShipHead.ShipDate
,Customer.Name
,ShipDtl.OrderNum
,ShipDtl.OrderLine
,ShipDtl.OrderRelNum
FROM
OrderHed
INNER JOIN OrderDtl
ON OrderHed.Company = OrderDtl.Company AND OrderHed.OrderNum = OrderDtl.OrderNum
INNER JOIN OrderRel
ON OrderDtl.Company = OrderRel.Company AND OrderDtl.OrderNum = OrderRel.OrderNum AND OrderDtl.OrderLine = OrderRel.OrderLine
INNER JOIN ShipDtl
ON OrderRel.Company = ShipDtl.Company AND OrderRel.OrderNum = ShipDtl.OrderNum AND OrderRel.OrderLine = ShipDtl.OrderLine AND OrderRel.OrderRelNum = ShipDtl.OrderRelNum
INNER JOIN ShipHead
ON ShipDtl.Company = ShipHead.Company AND ShipDtl.PackNum = ShipHead.PackNum
INNER JOIN Customer
ON ShipHead.Company = Customer.Company AND ShipHead.CustNum = Customer.CustNum
WHERE
OrderRel.OrderNum = 603205
You could try the following. If you wanted the last dated record for each entry person then change to the B:
SELECT
X.ReqDate,
X.EntryPerson,
X.ShipDate,
X.Name,
X.OrderNum,
X.OrderLine,
X.OrderRelNum
FROM
(
SELECT
ORl.ReqDate,
OH.EntryPerson,
SH.ShipDate,
rn = row_number() OVER(ORDER BY SH.ShipDate DESC),
--rn = row_number() OVER(PARTITION BY OH.EntryPerson ORDER BY SH.ShipDate DESC) --<<B
C.Name,
SD.OrderNum,
SD.OrderLine,
SD.OrderRelNum
FROM
OrderHed OH
INNER JOIN OrderDtl OD ON
OH.Company = OD.Company AND
OH.OrderNum = OD.OrderNum
INNER JOIN OrderRel ORl ON
OD.Company = ORl.Company AND
OD.OrderNum = ORl.OrderNum AND
OD.OrderLine = ORl.OrderLine
INNER JOIN ShipDtl SD ON
ORl.Company = SD.Company AND
ORl.OrderNum = SD.OrderNum AND
ORl.OrderLine = SD.OrderLine AND
ORl.OrderRelNum = SD.OrderRelNum
INNER JOIN ShipHead SH ON
SD.Company = SH.Company AND
SD.PackNum = SH.PackNum
INNER JOIN Customer C ON
SH.Company = C.Company AND
SH.CustNum = C.CustNum
WHERE
ORl.OrderNum = 603205
) X
WHERE X.rn = 1
P.S. why don't you use shorter aliases - that is part of the point of aliases

Tweak SQL query help

I have a big query as following, someone please tweak this query? i need to avoid this big group by ... :-)
SELECT COALESCE( SUM(total_retail), 0 ) total_retail,
COALESCE( SUM(meterial_sub_total), 0 ) meterial_sub_total,
COALESCE( MIN(po_template_group_by_code), 0 ) po_template_group_by_code,
COALESCE( MIN(po_template_sort_by_code), 0 ) po_template_sort_by_code
FROM
(
SELECT
COALESCE( CASE WHEN COALESCE(ihbol.valuation_method_code, pih.valuation_method_code, #default_valuation_method_code, 'i') IN ('r', 'i', 'l') THEN
COALESCE ( rmiretail.retail_price / rmiretail.unit_of_measure_quantity
/ COALESCE( uomcvrmi.atomic_conversion_factor * UOMrmi.factor, UOMrmi.factor ), 0 )
* poi.confirmed_quantity
* ( CASE WHEN poi.catch_weight_flag = 'y'
THEN ( poi.package_weight * COALESCE( uomcvpr.atomic_conversion_factor * UOMpr.factor, UOMpr.factor ) )
WHEN si.shipper_flag = 'y'
THEN ( meterial_data.linked_meterial_quantity * COALESCE( uomcvitm.atomic_conversion_factor * uomitm.factor, uomitm.factor ) )
ELSE ( COALESCE( uomcvpkg.atomic_conversion_factor * UOMpkg.factor, UOMpkg.factor ) )
END )
ELSE
NULL
END, 0 ) AS total_retail,
CASE WHEN MIN(s.rcv_using_po_default_cost_target_code) = 'p' AND MIN(po.status_code) <> 't'
THEN COALESCE( MIN(po.last_draft_total), 0 )
ELSE CASE WHEN meterial_data.linked_meterial_quantity IS NULL
THEN CASE WHEN poi.catch_weight_flag = 'y'
THEN COALESCE( poi.confirmed_quantity * poi.package_weight * spicost.net_supplier_price, 0 )
ELSE COALESCE( poi.confirmed_quantity * spicost.net_supplier_price, 0 )
END
ELSE 0
END
END AS meterial_sub_total
,po.po_template_group_by_code AS po_template_group_by_code
,po.po_template_sort_by_code AS po_template_sort_by_code
FROM purchase_order po
JOIN supplier s WITH (NOLOCK)
ON po.supplier_id = s.supplier_id
JOIN purchase_order_meterial poi WITH (NOLOCK)
ON po.purchase_order_id = poi.purchase_order_id
AND po.business_unit_id = poi.business_unit_id
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
AND poi.supplier_id = si.supplier_id
JOIN supplier_packaged_meterial spi WITH (NOLOCK)
ON spi.supplier_meterial_id = si.supplier_meterial_id
AND spi.supplier_id = #supplier_id:int
JOIN unit_of_measure uompkg WITH (NOLOCK)
ON uompkg.unit_of_measure_id = spi.packaged_in_uom_id
JOIN merch_bu_spi_cost_list spicost WITH (NOLOCK)
ON spicost.business_unit_id = #bu_id:int
AND spicost.supplier_id = si.supplier_id
AND spicost.supplier_meterial_id = si.supplier_meterial_id
AND spicost.packaged_meterial_id = spi.packaged_meterial_id
LEFT OUTER JOIN
(
SELECT poi.supplier_meterial_id AS supplier_meterial_id,
si.meterial_id AS linked_meterial_id,
NULL AS linked_meterial_uom,
NULL AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
UNION ALL
SELECT siil.supplier_meterial_id AS supplier_meterial_id,
siil.inventory_meterial_id AS linked_meterial_id,
siil.unit_of_measure_id AS linked_meterial_uom,
siil.inventory_meterial_quantity AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_inventory_meterial_list siil WITH (NOLOCK)
ON siil.supplier_id = #supplier_id:int
AND poi.supplier_meterial_id = siil.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
) meterial_data
ON meterial_data.supplier_meterial_id = si.supplier_meterial_id
LEFT OUTER JOIN meterial i
ON i.meterial_id = meterial_data.linked_meterial_id
LEFT OUTER JOIN meterial_hierarchy ih
ON ih.meterial_hierarchy_id = COALESCE(si.meterial_hierarchy_id, i.meterial_hierarchy_id)
LEFT OUTER JOIN meterial_hierarchy pih
ON ih.setstring LIKE pih.setstring + '%'
AND pih.meterial_hierarchy_level_id = #meterial_hierarchy_level_id
LEFT OUTER JOIN meterial_hierarchy_bu_override_list ihbol
ON ihbol.business_unit_id = #bu_id:int
AND ihbol.meterial_hierarchy_id = pih.meterial_hierarchy_id
LEFT OUTER JOIN retail_modified_meterial rmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = rmi.retail_meterial_id
AND rmi.retail_valuation_flag = 'y'
LEFT OUTER JOIN merch_bu_rmi_retail_list rmiretail WITH (NOLOCK)
ON rmiretail.retail_modified_meterial_id = rmi.retail_modified_meterial_id
AND rmiretail.business_unit_id = #bu_id:int
LEFT OUTER JOIN unit_of_measure uompr WITH (NOLOCK)
ON uompr.unit_of_measure_id = spi.priced_in_uom_id
LEFT OUTER JOIN unit_of_measure uomitm WITH (NOLOCK)
ON uomitm.unit_of_measure_id = meterial_data.linked_meterial_uom
LEFT OUTER JOIN unit_of_measure uomrmi WITH (NOLOCK)
ON uomrmi.unit_of_measure_id = rmi.unit_of_measure_id
LEFT OUTER JOIN meterial_uom_conversion uomcvitm WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvitm.meterial_id
AND uomitm.unit_of_measure_class_id = uomcvitm.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvrmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvrmi.meterial_id
AND uomrmi.unit_of_measure_class_id = uomcvrmi.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpr WITH (NOLOCK)
ON uomcvpr.meterial_id = meterial_data.linked_meterial_id
AND uomcvpr.unit_of_measure_class_id = uompr.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpkg WITH (NOLOCK)
ON uomcvpkg.meterial_id = meterial_data.linked_meterial_id
AND uomcvpkg.unit_of_measure_class_id = uompkg.unit_of_measure_class_id
WHERE po.purchase_order_id = #po_id:int
AND po.business_unit_id = #bu_id:int
GROUP BY poi.supplier_meterial_id, poi.confirmed_quantity, spicost.net_supplier_price,
meterial_data.linked_meterial_quantity,poi.catch_weight_flag,poi.package_weight,
ihbol.valuation_method_code, pih.valuation_method_code,rmiretail.retail_price,
rmiretail.unit_of_measure_quantity, uomcvrmi.atomic_conversion_factor, UOMrmi.factor,
UOMrmi.factor, uomcvpr.atomic_conversion_factor, UOMpr.factor, si.shipper_flag,
meterial_data.linked_meterial_quantity, uomcvitm.atomic_conversion_factor ,uomitm.factor,
uomitm.factor, uomcvpkg.atomic_conversion_factor,UOMpkg.factor, UOMpkg.factor,
po.po_template_group_by_code, po.po_template_sort_by_code
) resultTable
Try:
SELECT COALESCE( SUM(total_retail), 0 ) total_retail,
COALESCE( SUM(meterial_sub_total), 0 ) meterial_sub_total,
COALESCE( MIN(po_template_group_by_code), 0 ) po_template_group_by_code,
COALESCE( MIN(po_template_sort_by_code), 0 ) po_template_sort_by_code
FROM
(
SELECT
sum(COALESCE( CASE WHEN COALESCE(ihbol.valuation_method_code, pih.valuation_method_code, #default_valuation_method_code, 'i') IN ('r', 'i', 'l') THEN
COALESCE ( rmiretail.retail_price / rmiretail.unit_of_measure_quantity
/ COALESCE( uomcvrmi.atomic_conversion_factor * UOMrmi.factor, UOMrmi.factor ), 0 )
* poi.confirmed_quantity
* ( CASE WHEN poi.catch_weight_flag = 'y'
THEN ( poi.package_weight * COALESCE( uomcvpr.atomic_conversion_factor * UOMpr.factor, UOMpr.factor ) )
WHEN si.shipper_flag = 'y'
THEN ( meterial_data.linked_meterial_quantity * COALESCE( uomcvitm.atomic_conversion_factor * uomitm.factor, uomitm.factor ) )
ELSE ( COALESCE( uomcvpkg.atomic_conversion_factor * UOMpkg.factor, UOMpkg.factor ) )
END )
ELSE
NULL
END, 0 )) AS total_retail,
sum(CASE WHEN MIN(s.rcv_using_po_default_cost_target_code) = 'p' AND MIN(po.status_code) <> 't'
THEN COALESCE( MIN(po.last_draft_total), 0 )
ELSE CASE WHEN meterial_data.linked_meterial_quantity IS NULL
THEN CASE WHEN poi.catch_weight_flag = 'y'
THEN COALESCE( poi.confirmed_quantity * poi.package_weight * spicost.net_supplier_price, 0 )
ELSE COALESCE( poi.confirmed_quantity * spicost.net_supplier_price, 0 )
END
ELSE 0
END
END) AS meterial_sub_total
,po.po_template_group_by_code AS po_template_group_by_code
,po.po_template_sort_by_code AS po_template_sort_by_code
FROM purchase_order po
JOIN supplier s WITH (NOLOCK)
ON po.supplier_id = s.supplier_id
JOIN purchase_order_meterial poi WITH (NOLOCK)
ON po.purchase_order_id = poi.purchase_order_id
AND po.business_unit_id = poi.business_unit_id
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
AND poi.supplier_id = si.supplier_id
JOIN supplier_packaged_meterial spi WITH (NOLOCK)
ON spi.supplier_meterial_id = si.supplier_meterial_id
AND spi.supplier_id = #supplier_id:int
JOIN unit_of_measure uompkg WITH (NOLOCK)
ON uompkg.unit_of_measure_id = spi.packaged_in_uom_id
JOIN merch_bu_spi_cost_list spicost WITH (NOLOCK)
ON spicost.business_unit_id = #bu_id:int
AND spicost.supplier_id = si.supplier_id
AND spicost.supplier_meterial_id = si.supplier_meterial_id
AND spicost.packaged_meterial_id = spi.packaged_meterial_id
LEFT OUTER JOIN
(
SELECT poi.supplier_meterial_id AS supplier_meterial_id,
si.meterial_id AS linked_meterial_id,
NULL AS linked_meterial_uom,
NULL AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
UNION ALL
SELECT siil.supplier_meterial_id AS supplier_meterial_id,
siil.inventory_meterial_id AS linked_meterial_id,
siil.unit_of_measure_id AS linked_meterial_uom,
siil.inventory_meterial_quantity AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_inventory_meterial_list siil WITH (NOLOCK)
ON siil.supplier_id = #supplier_id:int
AND poi.supplier_meterial_id = siil.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
) meterial_data
ON meterial_data.supplier_meterial_id = si.supplier_meterial_id
LEFT OUTER JOIN meterial i
ON i.meterial_id = meterial_data.linked_meterial_id
LEFT OUTER JOIN meterial_hierarchy ih
ON ih.meterial_hierarchy_id = COALESCE(si.meterial_hierarchy_id, i.meterial_hierarchy_id)
LEFT OUTER JOIN meterial_hierarchy pih
ON ih.setstring LIKE pih.setstring + '%'
AND pih.meterial_hierarchy_level_id = #meterial_hierarchy_level_id
LEFT OUTER JOIN meterial_hierarchy_bu_override_list ihbol
ON ihbol.business_unit_id = #bu_id:int
AND ihbol.meterial_hierarchy_id = pih.meterial_hierarchy_id
LEFT OUTER JOIN retail_modified_meterial rmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = rmi.retail_meterial_id
AND rmi.retail_valuation_flag = 'y'
LEFT OUTER JOIN merch_bu_rmi_retail_list rmiretail WITH (NOLOCK)
ON rmiretail.retail_modified_meterial_id = rmi.retail_modified_meterial_id
AND rmiretail.business_unit_id = #bu_id:int
LEFT OUTER JOIN unit_of_measure uompr WITH (NOLOCK)
ON uompr.unit_of_measure_id = spi.priced_in_uom_id
LEFT OUTER JOIN unit_of_measure uomitm WITH (NOLOCK)
ON uomitm.unit_of_measure_id = meterial_data.linked_meterial_uom
LEFT OUTER JOIN unit_of_measure uomrmi WITH (NOLOCK)
ON uomrmi.unit_of_measure_id = rmi.unit_of_measure_id
LEFT OUTER JOIN meterial_uom_conversion uomcvitm WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvitm.meterial_id
AND uomitm.unit_of_measure_class_id = uomcvitm.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvrmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvrmi.meterial_id
AND uomrmi.unit_of_measure_class_id = uomcvrmi.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpr WITH (NOLOCK)
ON uomcvpr.meterial_id = meterial_data.linked_meterial_id
AND uomcvpr.unit_of_measure_class_id = uompr.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpkg WITH (NOLOCK)
ON uomcvpkg.meterial_id = meterial_data.linked_meterial_id
AND uomcvpkg.unit_of_measure_class_id = uompkg.unit_of_measure_class_id
WHERE po.purchase_order_id = #po_id:int
AND po.business_unit_id = #bu_id:int
GROUP BY po.po_template_group_by_code, po.po_template_sort_by_code
) resultTable
I think it should return the same results as the query above, although whether those results are what you actually want is a different matter...