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

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)

Related

Connecting Tableau to Teradata with Custom SQL Query

EDIT: Even if I try removing that 'AS' everywhere, I continue getting errors about things that seem like normal SQL commands. If I remove the 'AS', the next error I get is:
[IBM][CLI Driver][DB2] SQL0199N The use of the reserved word "CAST"
following "" is not valid. Expected tokens may include: ", )".
SQLSTATE=42601
Question:
I am trying to connect to Teradata with a Custom SQL Query, and while it is running perfectly in Teradata SQL Assistant, I keep getting errors when trying to run it in Tableau.
One of the errors looks like this, but even if I try to change something, a similar error will come up:
[IBM][CLI Driver][DB2] SQL0199N The use of the reserved word "AS"
following "" is not valid. Expected tokens may include: "JOIN CROSS
INNER LEFT RIGHT FULL (". SQLSTATE=42601
Here is the query (sorry, it's long):
WITH RQSTS AS(
select CAST( M.RQST_ID AS VARCHAR(20)) AS MASTER_RQST_ID,
M.RQST_TYP_CD
FROM PRTHD.HOST_RQST AS M --MASTER
WHERE M.MSTR_RQST_ID IS NULL
AND M.crt_user_id='SXB8NBS'
AND M.OCYC_SOQ_RSN_CD = 170
AND date(M.CRT_TS) >= CURRENT_DATE - 7 DAY
),
RQST_TYPE AS(
select R.MASTER_RQST_ID AS RQST_ID,
NRT.TYP_DESC AS HOST_TYPE
FROM RQSTS AS R
LEFT JOIN PRTHD.N_HOST_RQST_TYP AS NRT
ON R.RQST_TYP_CD = NRT.RQST_TYP_CD
GROUP BY R.MASTER_RQST_ID, NRT.TYP_DESC
),
PO_DETAILS AS(
select A.*
FROM (
SELECT distinct PRTHD.BYO_PO.DSVC_TYP_CD,
RT.RQST_ID,
RT.HOST_TYPE,
PRTHD.BYO_PO.PO_CMT_TXT,
PRTHD.BYO_PO.BYO_NBR,
CASE WHEN PRTHD.BYO_PO.DSVC_TYP_CD = 2 THEN RIGHT('00'||PRTHD.BYO_PO.BYO_NBR,2)
ELSE RIGHT('00'|| PRTHD.BYO_PO_LOC_SKU.LOC_NBR,2) END
|| PRTHD.BYO_PO.acct_po_typ_cd || RIGHT('00000'||PRTHD.BYO_PO.PO_CTRL_NBR,5) AS PO,
PRTHD.BYO_PO.ORD_REF_NBR,
PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR,
PRTHD.BYO_PO_LOC_SKU.LOC_NBR,
PRTHD.BYO_PO_LOC_SKU.SKU_NBR,
CAST(PRTHD.BYO_PO_LOC_SKU.ORD_QTY AS INTEGER) AS ORD_QTY,
PRTHD.BYO_PO.CRT_DT,
PRTHD.BYO_PO.PO_CTRL_NBR,
M.MVNDR_NM,
PRTHD.BYO_PO.MVNDR_NBR,
PRTHD.BYO_PO.OCYC_SOQ_RSN_CD AS RSN_CD
FROM ((PRTHD.BYO_PO AS BP INNER JOIN PRTHD.BYO_PO_LOC_SKU
ON (PRTHD.BYO_PO.ORD_SEQ_NBR = PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR)
AND (PRTHD.BYO_PO.PO_CTRL_NBR = PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR)
AND (PRTHD.BYO_PO.ACCT_PO_TYP_CD = PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD)
AND (PRTHD.BYO_PO.MKT_DC_NBR = PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR)
AND (PRTHD.BYO_PO.MKT_DC_IND = PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND)
AND (PRTHD.BYO_PO.BYO_NBR = PRTHD.BYO_PO_LOC_SKU.BYO_NBR))
INNER JOIN PRTHD.SKU
ON PRTHD.BYO_PO_LOC_SKU.SKU_NBR = PRTHD.SKU.SKU_NBR)
INNER JOIN PRTHD.BYO_PO_SKU
ON (PRTHD.SKU.SKU_NBR = PRTHD.BYO_PO_SKU.SKU_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.BYO_NBR = PRTHD.BYO_PO_SKU.BYO_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND = PRTHD.BYO_PO_SKU.MKT_DC_IND)
AND (PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR = PRTHD.BYO_PO_SKU.MKT_DC_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD = PRTHD.BYO_PO_SKU.ACCT_PO_TYP_CD)
AND (PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR = PRTHD.BYO_PO_SKU.PO_CTRL_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR = PRTHD.BYO_PO_SKU.ORD_SEQ_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.PO_LINE_NBR = PRTHD.BYO_PO_SKU.PO_LINE_NBR)
LEFT JOIN PRTHD.MVNDR AS M
ON M.MVNDR_NBR = PRTHD.BYO_PO.MVNDR_NBR
INNER JOIN RQST_TYPE AS RT
ON TRIM(SUBSTR(BP.PO_CMT_TXT,6,11)) = RT.RQST_ID
) AS A)
Select P.RQST_ID,
P.DSVC_TYP_CD,
CASE WHEN P.DSVC_TYP_CD =1 THEN 'DTS'
WHEN P.DSVC_TYP_CD =2 THEN 'RDC AGG'
WHEN P.DSVC_TYP_CD =3 THEN 'RDCX'
END AS DSVC_TYP_DESC ,
CASE WHEN P.DSVC_TYP_CD =2 AND S.STR_NBR IS NOT NULL THEN 'Y'
ELSE 'N' END AS RDC_AGG_PEG_FLG,
CASE WHEN P.DSVC_TYP_CD =2 AND S.STR_NBR IS NOT NULL THEN P.ORD_REF_NBR
ELSE P.PO END AS PO_NBR,
P.BYO_NBR,
P.PO_CTRL_NBR,
P.CRT_DT,
P.HOST_TYPE,
P.MVNDR_NBR,
P.MVNDR_NM,
CASE WHEN P.DSVC_TYP_CD =2 AND S.STR_NBR IS NOT NULL THEN AR.MKT_DC_NBR
ELSE P.MKT_DC_NBR END AS MKT_DC_NBR,
P.LOC_NBR,
COALESCE(SKU.MER_DEPT_NBR || '-' || D.SHRT_DEPT_NM,'') AS DEPT,
COALESCE(SKU.MER_CLASS_NBR || '-' || MC.SHRT_CLASS_DESC,'') AS CLASS,
COALESCE(SKU.MER_SUB_CLASS_NBR || '-' || MSC.SHRT_SUBCLASS_DESC,'') AS SUB_CLASS,
P.SKU_NBR,
P.ORD_QTY,
COALESCE(SD.AVG_DC_LCOST_AMT*COALESCE(P.ORD_QTY,0),
MSM.CURR_COST_AMT*COALESCE(P.ORD_QTY,0)) AS TOTAL_COST,
SD.AVG_DC_LCOST_AMT AS SD_COST,
MSM.CURR_COST_AMT AS STR_CURR_COST,
MSD.CURR_COST_AMT AS DC_CURR_COST,
P.PO_CMT_TXT,
P.RSN_CD
FROM PO_DETAILS AS P
--SKU HIERARCHY INFO
LEFT JOIN PRTHD.SKU AS SKU
ON SKU.SKU_NBR = P.SKU_NBR
LEFT JOIN PRTHD.DEPT AS D
ON SKU.MER_DEPT_NBR = D.DEPT_NBR
LEFT JOIN PRTHD.MER_CLASS AS MC
ON MC.MER_DEPT_NBR= SKU.MER_DEPT_NBR
AND MC.MER_CLASS_NBR = SKU.MER_CLASS_NBR
LEFT JOIN PRTHD.MER_SUB_CLASS AS MSC
ON MSC.MER_DEPT_NBR= SKU.MER_DEPT_NBR
AND MSC.MER_CLASS_NBR = SKU.MER_CLASS_NBR
AND MSC.MER_SUB_CLASS_NBR = SKU.MER_SUB_CLASS_NBR
LEFT JOIN PRTHD.MVNDR_SKU_DC AS MSD
ON MSD.MVNDR_NBR = P.MVNDR_NBR
AND MSD.SKU_NBR = P.SKU_NBR
AND MSD.DC_NBR = P.LOC_NBR
LEFT JOIN PRTHD.STR AS S
ON S.STR_NBR = P.LOC_NBR
LEFT JOIN PRTHD.SKU_DC AS SD
ON SD.DC_NBR=P.MKT_DC_NBR
AND SD.SKU_NBR=P.SKU_NBR
LEFT JOIN PRTHD.MVNDR_SKU_MKT AS MSM
ON MSM.MVNDR_NBR = P.MVNDR_NBR
AND MSM.SKU_NBR = P.SKU_NBR
AND MSM.MKT_NBR = S.MKT_NBR
LEFT JOIN PRTHD.AGG_RQST AS AR
ON AR.PO_NBR = P.ORD_REF_NBR
AND P.MVNDR_NBR = AR.MVNDR_NBR
AND SKU.MER_DEPT_NBR = AR.MER_DEPT_NBR
AND AR.ORD_DT >= P.CRT_DT
Can anyone help me figure out what might be going wrong here? Thank you!
Delete all the AS:
WITH RQSTS (
select CT(M.RQST_ID VARCHAR(20)) MTER_RQST_ID,
M.RQST_TYP_CD
FROM PRTHD.HOST_RQST M --MTER
WHERE M.MSTR_RQST_ID IS NULL
AND M.crt_user_id = 'SXB8NBS'
AND M.OCYC_SOQ_RSN_CD = 170
AND date(M.CRT_TS) >= CURRENT_DATE - 7 DAY
),
RQST_TYPE (
select R.MTER_RQST_ID RQST_ID,
NRT.TYP_DESC HOST_TYPE
FROM RQSTS R
LEFT JOIN PRTHD.N_HOST_RQST_TYP NRT ON R.RQST_TYP_CD = NRT.RQST_TYP_CD
GROUP BY R.MTER_RQST_ID,
NRT.TYP_DESC
),
PO_DETAILS (
select A.*
FROM (
SELECT distinct PRTHD.BYO_PO.DSVC_TYP_CD,
RT.RQST_ID,
RT.HOST_TYPE,
PRTHD.BYO_PO.PO_CMT_TXT,
PRTHD.BYO_PO.BYO_NBR,
CE
WHEN PRTHD.BYO_PO.DSVC_TYP_CD = 2 THEN RIGHT('00' || PRTHD.BYO_PO.BYO_NBR, 2)
ELSE RIGHT('00' || PRTHD.BYO_PO_LOC_SKU.LOC_NBR, 2)
END || PRTHD.BYO_PO.acct_po_typ_cd || RIGHT('00000' || PRTHD.BYO_PO.PO_CTRL_NBR, 5) PO,
PRTHD.BYO_PO.ORD_REF_NBR,
PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR,
PRTHD.BYO_PO_LOC_SKU.LOC_NBR,
PRTHD.BYO_PO_LOC_SKU.SKU_NBR,
CT(PRTHD.BYO_PO_LOC_SKU.ORD_QTY INTEGER) ORD_QTY,
PRTHD.BYO_PO.CRT_DT,
PRTHD.BYO_PO.PO_CTRL_NBR,
M.MVNDR_NM,
PRTHD.BYO_PO.MVNDR_NBR,
PRTHD.BYO_PO.OCYC_SOQ_RSN_CD RSN_CD
FROM (
(
PRTHD.BYO_PO BP
INNER JOIN PRTHD.BYO_PO_LOC_SKU ON (
PRTHD.BYO_PO.ORD_SEQ_NBR = PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR
)
AND (
PRTHD.BYO_PO.PO_CTRL_NBR = PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR
)
AND (
PRTHD.BYO_PO.ACCT_PO_TYP_CD = PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD
)
AND (
PRTHD.BYO_PO.MKT_DC_NBR = PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR
)
AND (
PRTHD.BYO_PO.MKT_DC_IND = PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND
)
AND (
PRTHD.BYO_PO.BYO_NBR = PRTHD.BYO_PO_LOC_SKU.BYO_NBR
)
)
INNER JOIN PRTHD.SKU ON PRTHD.BYO_PO_LOC_SKU.SKU_NBR = PRTHD.SKU.SKU_NBR
)
INNER JOIN PRTHD.BYO_PO_SKU ON (PRTHD.SKU.SKU_NBR = PRTHD.BYO_PO_SKU.SKU_NBR)
AND (
PRTHD.BYO_PO_LOC_SKU.BYO_NBR = PRTHD.BYO_PO_SKU.BYO_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND = PRTHD.BYO_PO_SKU.MKT_DC_IND
)
AND (
PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR = PRTHD.BYO_PO_SKU.MKT_DC_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD = PRTHD.BYO_PO_SKU.ACCT_PO_TYP_CD
)
AND (
PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR = PRTHD.BYO_PO_SKU.PO_CTRL_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR = PRTHD.BYO_PO_SKU.ORD_SEQ_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.PO_LINE_NBR = PRTHD.BYO_PO_SKU.PO_LINE_NBR
)
LEFT JOIN PRTHD.MVNDR M ON M.MVNDR_NBR = PRTHD.BYO_PO.MVNDR_NBR
INNER JOIN RQST_TYPE RT ON TRIM(SUBSTR(BP.PO_CMT_TXT, 6, 11)) = RT.RQST_ID
) A
)
Select P.RQST_ID,
P.DSVC_TYP_CD,
CE
WHEN P.DSVC_TYP_CD = 1 THEN 'DTS'
WHEN P.DSVC_TYP_CD = 2 THEN 'RDC AGG'
WHEN P.DSVC_TYP_CD = 3 THEN 'RDCX'
END DSVC_TYP_DESC,
CE
WHEN P.DSVC_TYP_CD = 2
AND S.STR_NBR IS NOT NULL THEN 'Y'
ELSE 'N'
END RDC_AGG_PEG_FLG,
CE
WHEN P.DSVC_TYP_CD = 2
AND S.STR_NBR IS NOT NULL THEN P.ORD_REF_NBR
ELSE P.PO
END PO_NBR,
P.BYO_NBR,
P.PO_CTRL_NBR,
P.CRT_DT,
P.HOST_TYPE,
P.MVNDR_NBR,
P.MVNDR_NM,
CE
WHEN P.DSVC_TYP_CD = 2
AND S.STR_NBR IS NOT NULL THEN AR.MKT_DC_NBR
ELSE P.MKT_DC_NBR
END MKT_DC_NBR,
P.LOC_NBR,
COALESCE(SKU.MER_DEPT_NBR || '-' || D.SHRT_DEPT_NM, '') DEPT,
COALESCE(
SKU.MER_CLS_NBR || '-' || MC.SHRT_CLS_DESC,
''
) CLS,
COALESCE(
SKU.MER_SUB_CLS_NBR || '-' || MSC.SHRT_SUBCLS_DESC,
''
) SUB_CLS,
P.SKU_NBR,
P.ORD_QTY,
COALESCE(
SD.AVG_DC_LCOST_AMT * COALESCE(P.ORD_QTY, 0),
MSM.CURR_COST_AMT * COALESCE(P.ORD_QTY, 0)
) TOTAL_COST,
SD.AVG_DC_LCOST_AMT SD_COST,
MSM.CURR_COST_AMT STR_CURR_COST,
MSD.CURR_COST_AMT DC_CURR_COST,
P.PO_CMT_TXT,
P.RSN_CD
FROM PO_DETAILS P --SKU HIERARCHY INFO
LEFT JOIN PRTHD.SKU SKU ON SKU.SKU_NBR = P.SKU_NBR
LEFT JOIN PRTHD.DEPT D ON SKU.MER_DEPT_NBR = D.DEPT_NBR
LEFT JOIN PRTHD.MER_CLS MC ON MC.MER_DEPT_NBR = SKU.MER_DEPT_NBR
AND MC.MER_CLS_NBR = SKU.MER_CLS_NBR
LEFT JOIN PRTHD.MER_SUB_CLS MSC ON MSC.MER_DEPT_NBR = SKU.MER_DEPT_NBR
AND MSC.MER_CLS_NBR = SKU.MER_CLS_NBR
AND MSC.MER_SUB_CLS_NBR = SKU.MER_SUB_CLS_NBR
LEFT JOIN PRTHD.MVNDR_SKU_DC MSD ON MSD.MVNDR_NBR = P.MVNDR_NBR
AND MSD.SKU_NBR = P.SKU_NBR
AND MSD.DC_NBR = P.LOC_NBR
LEFT JOIN PRTHD.STR S ON S.STR_NBR = P.LOC_NBR
LEFT JOIN PRTHD.SKU_DC SD ON SD.DC_NBR = P.MKT_DC_NBR
AND SD.SKU_NBR = P.SKU_NBR
LEFT JOIN PRTHD.MVNDR_SKU_MKT MSM ON MSM.MVNDR_NBR = P.MVNDR_NBR
AND MSM.SKU_NBR = P.SKU_NBR
AND MSM.MKT_NBR = S.MKT_NBR
LEFT JOIN PRTHD.AGG_RQST AR ON AR.PO_NBR = P.ORD_REF_NBR
AND P.MVNDR_NBR = AR.MVNDR_NBR
AND SKU.MER_DEPT_NBR = AR.MER_DEPT_NBR
AND AR.ORD_DT >= P.CRT_DT

Access SQL Sum Duplicating Rows

I'm trying to write an Access SQL Query to get some values with a sub-select and sum a bunch of data but when I run the query the data is getting duplicated.
HereĀ“s my query
SELECT
tt.TransportType,
rp.duns AS Duns,
rp.part AS Part,
rp.plant AS Plant,
rr.Route AS Route,
rr.RouteComp,
tt.TransLength*tt.TransWidth*tt.TransHeight AS [Capacidade],
len(rr.CurrentFrequency) AS [Frequencia],
Capacidade*Frequencia AS Cap_Disp,
s.Cap_Disp*s.FrequenciaTotal AS Cap_Total,
s.FrequenciaTotal,
Cap_Disp/Cap_Total AS Rateio,
FROM ((((tblRoutesParts rp
INNER JOIN tbl20week w ON rp.duns = w.duns
AND rp.part = w.prt
AND rp.plant = w.plant)
INNER JOIN tblRoutesRoutes rr ON rp.Route = rr.Route)
INNER JOIN tblTransportTypes tt ON tt.TransportType = rr.TransportType)
INNER JOIN (SELECT tt.TransportType, rp.duns, rp.part, rp.plant,
sum(len(rr.CurrentFrequency)) as FrequenciaTotal,
sum((tt.TransLength*tt.TransWidth*tt.TransHeight)*(len(rr.CurrentFrequency))) AS Cap_Disp
from ( tblRoutesParts rp
INNER JOIN tblRoutesRoutes rr ON rp.Route = rr.Route)
INNER JOIN tblTransportTypes tt ON tt.TransportType = rr.TransportType
GROUP BY tt.TransportType,
rp.duns,
rp.part,
rp.plant) s ON s.duns= rp.duns
AND s.part = rp.part
AND s.plant = rp.plant)
WHERE left(rp.Route, 1) <> 'L'
and rp.duns = '903323939'
and rp.part = '24584938'
and rp.plant = 'BE'
and rr.Route = 'FRW.A0001'
And here's the output:
Like you see the data is duplicated only at the sum fields!
Can anyone help me?
Try joining your 's' ON s.TransportType = tt.TransportType. You may be getting multiple rows when you inner join s.
SELECT
tt.TransportType,
rp.duns AS Duns,
rp.part AS Part,
rp.plant AS Plant,
rr.Route AS Route,
rr.RouteComp,
tt.TransLength*tt.TransWidth*tt.TransHeight AS [Capacidade],
len(rr.CurrentFrequency) AS [Frequencia],
Capacidade*Frequencia AS Cap_Disp,
s.Cap_Disp*s.FrequenciaTotal AS Cap_Total,
s.FrequenciaTotal,
Cap_Disp/Cap_Total AS Rateio,
FROM ((((tblRoutesParts rp
INNER JOIN tbl20week w ON rp.duns = w.duns
AND rp.part = w.prt
INNER JOIN tblRoutesRoutes rr ON rp.Route = rr.Route)
INNER JOIN tblTransportTypes tt ON tt.TransportType = rr.TransportType)
INNER JOIN (SELECT tt.TransportType, rp.duns, rp.part, rp.plant,
sum(len(rr.CurrentFrequency)) as FrequenciaTotal,
sum((tt.TransLength*tt.TransWidth*tt.TransHeight)*(len(rr.CurrentFrequency))) AS Cap_Disp
from ( tblRoutesParts rp
INNER JOIN tblRoutesRoutes rr ON rp.Route = rr.Route)
INNER JOIN tblTransportTypes tt ON tt.TransportType = rr.TransportType
GROUP BY tt.TransportType,
rp.duns,
rp.part,
rp.plant) s ON s.duns= rp.duns
AND s.part = rp.part
AND s.plant = rp.plant
AND s.TransportType = tt.TransportType)
WHERE left(rp.Route, 1) <> 'L'
and rp.duns = '903323939'
and rp.part = '24584938'
and rp.plant = 'BE'
and rr.Route = 'FRW.A0001'

Selecting rows with MAX(Column value), DISTINCT by another column in SQL

I have two tables that I'm having difficulty with. OrderHed & UD11. OrderHed has 1 value for OrderNum=70960, but UD11 has 4 records for 70960.
I'm trying to return the max value of UD11.Key5 as a distinct record - what am I doing wrong?
Thanks!
SELECT TOP (100) PERCENT OrderHed.OrderNum,
OrderHed.OpenOrder,
OrderHed.OrderDate,
OrderRel.Plant,
OrderHed.EntryPerson,
OrderHed.Company,
Erp.Customer.CustID,
Erp.Customer.NAME,
Erp.InvcDtl.InvoiceNum,
SUM(OrderDtl.ExtPriceDtl) AS Expr1,
OrderHed.PONum,
Ice.UD11.Key1,
Ice.UD11.Key2,
Ice.UD11.Key3,
Ice.UD11.Key4,
MAX(Ice.UD11.Key5) AS Expr2,
Ice.UD11.Character01,
Ice.UD11.Number01,
Ice.UD11.Date01,
Ice.UD11.Date02,
Ice.UD11.Date03,
Ice.UD11.ShortChar01,
Ice.UD11.ShortChar02,
Ice.UD11.ShortChar03,
Ice.UD11.ShortChar04,
Ice.UD11.ShortChar05,
OrderHed.OrderComment
FROM Erp.Customer
RIGHT JOIN Ice.UD11
RIGHT JOIN Erp.OrderHed AS OrderHed ON Ice.UD11.Company = OrderHed.Company
AND Ice.UD11.Key1 = OrderHed.OrderNum
LEFT JOIN Erp.OrderRel AS OrderRel
RIGHT JOIN Erp.OrderDtl AS OrderDtl ON OrderRel.Company = OrderDtl.Company
AND OrderRel.OrderNum = OrderDtl.OrderNum
AND OrderRel.OrderLine = OrderDtl.OrderLine ON OrderHed.Company = OrderDtl.Company
AND OrderHed.OrderNum = OrderDtl.OrderNum ON Erp.Customer.Company = OrderHed.Company
AND Erp.Customer.CustNum = OrderHed.CustNum LEFT JOIN Erp.InvcDtl RIGHT JOIN Erp.ShipDtl ON Erp.InvcDtl.Company = Erp.ShipDtl.Company
AND Erp.InvcDtl.OrderNum = Erp.ShipDtl.OrderNum
AND Erp.InvcDtl.OrderLine = Erp.ShipDtl.OrderLine
AND Erp.InvcDtl.OrderRelNum = Erp.ShipDtl.OrderRelNum ON OrderRel.Company = Erp.ShipDtl.Company
AND OrderRel.OrderNum = Erp.ShipDtl.OrderNum
AND OrderRel.OrderLine = Erp.ShipDtl.OrderLine
AND OrderRel.OrderRelNum = Erp.ShipDtl.OrderRelNum GROUP BY OrderHed.OrderNum,
OrderHed.OrderDate,
OrderRel.Plant,
OrderHed.EntryPerson,
OrderHed.Company,
OrderHed.OpenOrder,
Erp.Customer.CustID,
Erp.Customer.NAME,
Erp.InvcDtl.InvoiceNum,
OrderHed.PONum,
Ice.UD11.Key1,
Ice.UD11.Key2,
Ice.UD11.Key3,
Ice.UD11.Key4,
Ice.UD11.Character01,
Ice.UD11.Number01,
Ice.UD11.Date01,
Ice.UD11.Date02,
Ice.UD11.Date03,
Ice.UD11.ShortChar01,
Ice.UD11.ShortChar02,
Ice.UD11.ShortChar03,
Ice.UD11.ShortChar04,
Ice.UD11.ShortChar05,
OrderHed.OrderComment HAVING (OrderHed.Company = N'011')
AND (Erp.InvcDtl.InvoiceNum IS NULL)
AND (OrderHed.OrderNum = 70960)
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY OrderNum ORDER BY key5 DESC) rn
FROM (... /* my huge query */) q
) q
WHERE rn = 1

How to optimize left join subqueries in oracle

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.

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