Could use some pointers to create dat file from sql query - sql

I could use some pointers on my query I have three external tables that i need to combine and create a .dat-file. But my query isn't very efficient and could use some help on fixing/improving this one. It consist of two part one main table which is dc_item_loc_sourcing (1) and two translation tables dc_ccn190_sid_vtb(2) and dc_item_loc_vert_pim(3). If the item + loc combination doesn't exist in 1 & 2 it should check 1 & 3.
SET heading OFF;
SET feedback OFF;
SET verify OFF;
SET echo OFF;
SET linesize 1000;
SET trimspool ON;
SET termout OFF;
SET newpage NONE;
SPOOL ../data/dc_sourcing.dat;
SELECT DISTINCT TO_CHAR(item)
|| '|' ||store
|| '|' ||source_method
|| '|' ||primary_supp
|| '|' ||source_wh
|| '|' ||actie
|| '|' ||reward_eligible_ind
FROM ((SELECT dpac_tbl.item
,st.store
,dc_iloc.source_method
,dc_iloc.primary_supp
,dc_iloc.source_wh
,dc_iloc.actie
,dc_iloc.reward_eligible_ind
,MAX(dc_iloc.source_method) OVER (PARTITION BY dpac_tbl.item,st.store) max_src_pack
FROM dc_item_loc_sourcing dc_iloc ,
dc_ccn190_sid_vtb dpac_tbl ,
store st ,
item_master im ,
item_loc il
WHERE dc_iloc.dpac = dpac_tbl.dpac
AND dpac_tbl.item = im.item
AND CAST(dc_iloc.loc AS VARCHAR2(150byte)) = st.store_name_secondary
AND st.store = il.loc
AND dpac_tbl.item = il.item
AND im.status = 'A'
AND st.store_close_date >= SYSDATE
AND il.status = 'A'
AND dpac_tbl.ITEM NOT IN
(SELECT IA.ITEM
FROM ITEM_ATTRIBUTES IA
WHERE IA.SH_STORE_ORDER_UNIT = 'N'
AND IA.SH_TRADE_UNIT = 'Y')
UNION
SELECT DISTINCT pi.item
,st.store
,dc_iloc.source_method
,dc_iloc.primary_supp
,dc_iloc.source_wh
,dc_iloc.actie
,dc_iloc.reward_eligible_ind
,MAX(dc_iloc.source_method) OVER (PARTITION BY pi.item,st.store) max_src_pack
FROM dc_item_loc_sourcing dc_iloc ,
dc_ccn190_sid_vtb dpac_tbl ,
store st ,
packitem pi ,
item_master im ,
item_loc il
WHERE dc_iloc.dpac = dpac_tbl.dpac
AND pi.pack_no = dpac_tbl.item
AND pi.item = im.item
AND CAST(dc_iloc.loc AS VARCHAR2(150byte)) = st.store_name_secondary
AND il.item = pi.item
AND il.loc = st.store
AND im.status = 'A'
AND im.dept NOT IN (900,910,920,930)
AND st.store_close_date >= SYSDATE
AND il.status = 'A'
AND PI.ITEM NOT IN
(SELECT IA.ITEM
FROM ITEM_ATTRIBUTES IA
WHERE IA.SH_STORE_ORDER_UNIT = 'N'
AND IA.SH_TRADE_UNIT = 'Y'))
UNION
(SELECT dpac_tbl.item ,
st.store ,
dc_iloc.source_method ,
dc_iloc.primary_supp ,
dc_iloc.source_wh ,
dc_iloc.actie ,
dc_iloc.reward_eligible_ind
,MAX(dc_iloc.source_method) OVER (PARTITION BY dpac_tbl.item,st.store) max_src_pack
FROM dc_item_loc_sourcing dc_iloc ,
dc_item_loc_vert_pim dpac_tbl ,
store st ,
item_master im ,
item_loc il
WHERE dc_iloc.dpac = dpac_tbl.dpac
AND dpac_tbl.item = im.item
AND CAST(dc_iloc.loc AS VARCHAR2(150 byte)) = st.store_name_secondary
AND il.item = dpac_tbl.item
AND il.loc = st.store
AND im.status = 'A'
AND dpac_tbl.artikel_type_lms NOT IN ('V','S')
AND st.store_close_date >= SYSDATE
AND il.status = 'A'
AND inventory_item_status_code = 'Active'
AND dpac_tbl.ITEM NOT IN
(SELECT IA.ITEM
FROM ITEM_ATTRIBUTES IA
WHERE IA.SH_STORE_ORDER_UNIT = 'N'
AND IA.SH_TRADE_UNIT = 'Y')
UNION
SELECT DISTINCT pi.item ,
st.store ,
dc_iloc.source_method ,
dc_iloc.primary_supp ,
dc_iloc.source_wh ,
dc_iloc.actie ,
dc_iloc.reward_eligible_ind
,MAX(dc_iloc.source_method) OVER (PARTITION BY pi.item,st.store) max_src_pack
FROM dc_item_loc_sourcing dc_iloc ,
dc_item_loc_vert_pim dpac_tbl ,
store st ,
packitem pi ,
item_master im ,
item_loc il
WHERE dc_iloc.dpac = dpac_tbl.dpac
AND pi.pack_no = dpac_tbl.item
AND pi.item = im.item
AND CAST(dc_iloc.loc AS VARCHAR2(150 byte)) = st.store_name_secondary
AND il.item = pi.item
AND il.loc = st.store
AND im.status = 'A'
AND dpac_tbl.artikel_type_lms NOT IN ('V','S')
AND im.dept NOT IN (900,910,920,930)
AND st.store_close_date >= SYSDATE
AND il.status = 'A'
AND inventory_item_status_code = 'Active'
AND pi.ITEM NOT IN
(SELECT IA.ITEM
FROM ITEM_ATTRIBUTES IA
WHERE IA.SH_STORE_ORDER_UNIT = 'N'
AND IA.SH_TRADE_UNIT = 'Y')))
WHERE source_method = max_src_pack;
SPOOL OFF;

This hasn't been tested - I'm away from an SQL instance at the moment, and obviously I don't have access to your tables. I also don't make any guarantee about performance, as I don't know about current indicies.
Your biggest problem appears to stem from using the implicit-join syntax. Don't use it, it's an anti-pattern; it also allows for some 'surprising' behaviour. Always explicitly specify your joins, and put (as many as possible) relevant conditions in the ON clause - only use the WHERE clause when dealing with the table reference in the FROM clause.
I also have a huge problem with this line:
AND CAST(dc_iloc.loc AS VARCHAR2(150byte)) = st.store_name_secondary
You will not (likely... there are some caveats) be using an index on this comparison, which won't help. It's also a terrible thing, semantically, to join on - why is an item-location table keyed by (apparently) the store name? It should by keyed by store id - which should be the same datatype (no conversions), and should be the internal id, not something as transient as a 'name'.
WITH Excluded_Item (item) as (SELECT DISTINCT item
FROM Item_Attributes
WHERE sh_store_order_unit = 'N'
AND sh_trade_unit = 'Y'), -- These should be 1/0 flags
-- (char or numeric)
-- or boolean, if supported
SELECT CAST(item as CHAR)
|| '|' || loc
|| '|' || source_method
|| '|' || primary_supp
|| '|' || source_wh
|| '|' || actie
|| '|' || reward_eligible_ind
FROM(SELECT DISTINCT c.item, c.loc,
a.source_method, a.primary_supp, a.source_wh, a.actie,
a.reward_eligible_ind,
MAX(a.source_method)
OVER(PARTITION BY c.item, c.loc) as maxSourcePack
-- this should be indexed
FROM dc_item_loc_sourcing as a
JOIN store as b
ON b.store_name_secondary = CAST(a.loc as VARCHAR2(150 byte))
AND b.store_close_date >= CURRENT_DATE
JOIN item_loc as c
ON c.loc = b.store
AND c.status = 'A'
JOIN item_master as d
ON d.status = 'A'
AND d.item = c.item
LEFT JOIN Excluded_Item as e
ON e.item = d.item
LEFT JOIN dc_ccn190_sid_vtb as f
ON f.dpac = a.dpac
LEFT JOIN dc_item_loc_vert_pim as g
ON g.dpac = a.dpac
AND g.artikel_type_lms NOT IN ('V', 'S')
AND inventory_item_status_code = 'Active' -- really? And where is this from?
LEFT JOIN packitem as h
ON (h.pack_no = f.item OR h.pack_no = g.item)
AND h.item = d.item
AND d.dept NOT IN (900, 910, 920, 930)
WHERE e.item IS NULL
AND (h.item IS NOT NULL
OR (h.item IS NULL AND (f.item = d.item OR g.item = d.item))) ) as h
WHERE source_method = maxSourcepack
I believe this is correct, although a definition of your tables (and sample data) would help immensely in this regard - especially in how packitem is defined.

Related

How can I sum the total based on a column in Firebird 2.5

How can get totalizations out of a group, especifically in Firebird 2.5.
I have the following query, it's big but it's simple, it has only some inner joins that are correlated.
SELECT "patrimônio", porc_residual AS "percentual residual", vida_util AS "vida útil",
vida_util_meses "vida útil meses", valor_base AS "valor aquisição/valor reavaliação",
"data de incorporação", VALOR_DEPRECIADO AS "valor depreciado" ,
grupo_audesp AS "grupo contábil", sum(dt_depreciado) over(ORDER BY grupo_audesp ) td
FROM
(
SELECT m.nome AS "patrimônio", t.PORC_RESIDUAL, t.VIDA_UTIL, t.VIDA_UTIL_MESES,
lpad(EXTRACT(DAY FROM t.dt_cadastro),2, '0') || '/' || lpad(EXTRACT(month FROM t.dt_cadastro),2, '0') || '/' || EXTRACT(year FROM t.dt_cadastro) "data de incorporação"
,t.placa, GA.ID_AUDESP, GA.NOME AS GRUPO_AUDESP,
T.VALOR as valor,
CASE WHEN (SELECT min(D.VALOR_NOVO)
FROM patrimonio_depreciacao D WHERE D.id_tombamento = T.id_tombamento
AND T.ID_ORGAO = '030000' AND T.SITUACAO IN('A','B')
AND D.REFERENCIA2 >=202201 AND D.REFERENCIA2 <=202201 ) IS NULL THEN(
case when (select max(d.valor_anterior)
from patrimonio_depreciacao D where D.id_tombamento = T.id_tombamento and
T.SITUACAO IN('A','B')
AND d.referencia2 >202201 ) IS NULL THEN T.VALOR_ATUAL ELSE
(select max(d.valor_anterior)
from patrimonio_depreciacao D where D.id_tombamento = T.id_tombamento and
T.SITUACAO IN('A','B')
AND d.referencia2 >202201 )
END)
ELSE
(SELECT min(D.VALOR_NOVO)
FROM patrimonio_depreciacao D WHERE D.id_tombamento = T.id_tombamento
AND T.ID_ORGAO = '030000' AND T.SITUACAO IN('A','B')
AND D.REFERENCIA2 >=202201 AND D.REFERENCIA2 <=202201 ) END as valor_atual,
(SELECT sum(D.VALOR_DEPRECIADO)
FROM patrimonio_depreciacao D WHERE D.id_tombamento = T.id_tombamento
AND T.ID_ORGAO = '030000'
AND D.REFERENCIA2 >=202201 AND D.REFERENCIA2 <=202201 ) as valor_depreciado, T.DT_AQUISICAO,
PS.NOME,
case when (select first 1 pri.vl_reavaliacao from patrimonio_reavaliacao_item pri
inner join patrimonio_reavaliacao pr on pr.id_reavaliacao = pri.id_reavaliacao_item
where pri.id_tombamento = t.id_tombamento
and pr.data<='2022-01-31'
and pr.encerrado ='S'
order by pr.data desc) is null then t.vl_base_depreciacao
else
(select first 1 pri.vl_reavaliacao from patrimonio_reavaliacao_item pri
inner join patrimonio_reavaliacao pr on pr.id_reavaliacao = pri.id_reavaliacao_item
where pri.id_tombamento = t.id_tombamento
and pr.data <= '2022-01-31'
and pr.encerrado ='S'
order by pr.data desc) end as valor_base
FROM PATRIMONIO_TOMBAMENTO T
LEFT JOIN PATRIMONIO_GRUPO_AUDESP GA ON GA.ID_GRUPO_AUDESP = T.ID_GRUPO_AUDESP
LEFT JOIN ESTOQUE_MATERIAL M ON M.ID_MATERIAL = T.ID_MATERIAL
LEFT JOIN PATRIMONIO_SETOR PS ON (T.ID_SETOR = PS.ID_SETOR)
WHERE T.ID_ORGAO = '030000'
AND (T.SITUACAO IN('A') or ( T.SITUACAO = 'B' AND T.DT_BAIXA >'2022-01-31'))
AND (T.DT_REATIVADO IS NULL OR T.DT_REATIVADO<= '2022-01-31' or (T.DT_BAIXA >'2022-01-31'))
AND T.dt_cadastro <= '2022-01-31'
AND PS.TIPO_SETOR = 'S'
ORDER BY GA.ID_AUDESP, t.DT_CADASTRO) t
I think most import is the result
I want to sum "valor depreciado" and "valor aquisição/valor reavaliação" based on those groups.
to make it simple it could be an additional column that repeats the sum in all rows for the entire group.

Invalid column in unpivot CTE query

I am getting the error Invalid column name MERCHANDISE_AMT'. on the below CTE unpivot query. I am selecting in MERCHANDISE_AMT in both queries so I do not understand why it's coming up as invalid. What am I overlooking here? If I take MERCHANDISE_AMT out of the unpivot than it runs, but I need to use this column for unpivoting. (unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
;WITH CTE AS (
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END AS LINE_TYPE , A.MERCHANDISE_AMT, CASE WHEN CONVERT(CHAR(24),A.QTY_VCHR) = '0' THEN '' ELSE B.QTY_VCHR END AS INVOICE_QTY, CASE WHEN CONVERT(CHAR(24),A.UNIT_PRICE) = '0' THEN '' ELSE A.UNIT_PRICE END AS UNIT_PRICE , A.UNIT_OF_MEASURE, REPLACE(A.DESCR,'"','') AS DESCR , '' AS BLANK1, '' AS BLANK2--A.PO_ID, A.LINE_NBR,
, ''AS BLANK3, ''AS BLANK4, --A.SCHED_NBR, B.PO_DIST_LINE_NUM,
''AS BLANK5,
''AS BLANK6,''AS BLANK7,''AS BLANK777,''AS BLANK8,''AS BLANK9,''AS BLANK10,''AS BLANK11,''AS BLANK12,
F.ORACLE_ENTITY + '.' + F.ORACLE_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '881' THEN '000'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '889' THEN '950'
WHEN B.BUSINESS_UNIT_GL = '11000' AND H.DEPTID = '775' THEN '000'
WHEN B.DEPTID = '' THEN '000'
ELSE B.DEPTID END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000.' + '000000' AS SEGMENTS ,
''AS BLANK13, '2021/05/31' AS DATE1, ''AS BLANK14,''AS BLANK15,''AS BLANK16,''AS BLANK17, ''AS BLANK18, --A.SHIPTO_ID
''AS BLANK19,''AS BLANK199,''AS BLANK1999,''AS BLANK20,''AS BLANK21,''AS BLANK211,''AS BLANK22,''AS BLANK23,''AS BLANK24,''AS BLANK25,''AS BLANK26,''AS BLANK27,''AS BLANK28,''AS BLANK29,''AS BLANK30,''AS BLANK31,
''AS BLANK134,
''AS BLANK32, ''AS BLANK33, ''AS BLANK34, --A.SALETX_AMT --<--IS THIS THE RIGHT FIELD?
''AS BLANK35, ''AS BLANK36, --B.QTY_VCHR,
'N'AS BLANK37, ''AS BLANK38,''AS BLANK39,''AS BLANK40,''AS BLANK41,''AS BLANK411,''AS BLANK42, ''AS BLANK43, ''AS BLANK44,''AS BLANK45,''AS BLANK46,''AS BLANK47,''AS BLANK48,''AS BLANK49,''AS BLANK50,''AS BLANK51,''AS BLANK52,''AS BLANK53,''AS BLANK54,''AS BLANK55,''AS BLANK56,''AS BLANK57,''AS BLANK58,''AS BLANK59,''AS BLANK60,''AS BLANK61,''AS BLANK62,''AS BLANK63,''AS BLANK64,''AS BLANK65,''AS BLANK66,''AS BLANK67,''AS BLANK68,''AS BLANK69,''AS BLANK70,''AS BLANK71,''AS BLANK72,''AS BLANK73,''AS BLANK74,''AS BLANK75,''AS BLANK76,''AS BLANK77,''AS BLANK78,''AS BLANK79,''AS BLANK80,
''AS BLANK81,''AS BLANK82,''AS BLANK83,''AS BLANK84,''AS BLANK85,''AS BLANK86,''AS BLANK87,''AS BLANK88,''AS BLANK89,''AS BLANK90,''AS BLANK91,''AS BLANK92,''AS BLANK93,''AS BLANK94,''AS BLANK95,''AS BLANK96,''AS BLANK97,''AS BLANK98,''AS BLANK99,''AS BLANK100,''AS BLANK101,''AS BLANK102,''AS BLANK103,''AS BLANK104,''AS BLANK105,''AS BLANK106,''AS BLANK107,''AS BLANK108,''AS BLANK109,''AS BLANK110,''AS BLANK111,''AS BLANK112,''AS BLANK113,''AS BLANK114,''AS BLANK115,''AS BLANK116,''AS BLANK117,''AS BLANK118,''AS BLANK119,''AS BLANK120,''AS BLANK121,''AS BLANK122,''AS BLANK123,''AS BLANK124,''AS BLANK125,''AS BLANK126,''AS BLANK127,''AS BLANK128,''AS BLANK129,''AS BLANK130,''AS BLANK131,'' AS BLANK132
, C.SALETX_AMT, C.FREIGHT_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM AND D.WTHD_ENTITY = 'IRS'
LEFT OUTER JOIN PS_VCHR_LINE_WTHD DD ON DD.BUSINESS_UNIT = D.BUSINESS_UNIT AND DD.VOUCHER_ID = D.VOUCHER_ID AND DD.VOUCHER_LINE_NUM = D.VOUCHER_LINE_NUM AND DD.WTHD_ENTITY = 'PA'
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND C.ACCOUNTING_DT < '06-01-2021'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
AND C.MATCH_STATUS_VCHR = 'M'
AND C.APPR_STATUS = 'A'
AND B.VOUCHER_ID = '00720667' )
SELECT INVOICE_ID, VOUCHER_LINE_NUM - 1 + row_number() over (PARTITION BY INVOICE_ID, VOUCHER_LINE_NUM ORDER BY VOUCHER_LINE_NUM) AS VOUCHER_LINE_NUM,
LINE_TYPE, MERCHANDISE_AMT, INVOICE_QTY, UNIT_PRICE, UNIT_OF_MEASURE, DESCR , BLANK1, BLANK2--A.PO_ID, A.LINE_NBR,
, BLANK3, BLANK4,
BLANK5, BLANK6,BLANK7,BLANK777,BLANK8,BLANK9,BLANK10,BLANK11,BLANK12,
SEGMENTS, BLANK13, DATE1, BLANK14,BLANK15,BLANK16,BLANK17, BLANK18,
BLANK19,BLANK199,BLANK1999,BLANK20,BLANK21,BLANK211,BLANK22,BLANK23,BLANK24,BLANK25,BLANK26,BLANK27,BLANK28,
BLANK29,BLANK30,BLANK31,
BLANK133,
BLANK134, BLANK32, BLANK33, BLANK34,
BLANK35, BLANK36,
BLANK37, BLANK38,BLANK39,BLANK40,BLANK41,BLANK411,BLANK42, BLANK43, BLANK44,BLANK45,BLANK46,BLANK47,BLANK48,BLANK49,BLANK50,BLANK51,BLANK52,BLANK53,BLANK54,BLANK55,BLANK56,BLANK57,BLANK58,BLANK59,BLANK60,BLANK61,BLANK62,BLANK63,BLANK64,BLANK65,BLANK66,BLANK67,BLANK68,BLANK69,BLANK70,BLANK71,BLANK72,BLANK73,BLANK74,BLANK75,BLANK76,BLANK77,BLANK78,BLANK79,BLANK80,
BLANK81,BLANK82,BLANK83,BLANK84,BLANK85,BLANK86,BLANK87,BLANK88,BLANK89,BLANK90,BLANK91,BLANK92,BLANK93,BLANK94,BLANK95,BLANK96,BLANK97,BLANK98,BLANK99,BLANK100,BLANK101,BLANK102,BLANK103,BLANK104,BLANK105,BLANK106,BLANK107,BLANK108,BLANK109,BLANK110,BLANK111,BLANK112,BLANK113,BLANK114,BLANK115,BLANK116,BLANK117,BLANK118,BLANK119,BLANK120,BLANK121,BLANK122,BLANK123,BLANK124,BLANK125,BLANK126,BLANK127,BLANK128,BLANK129,BLANK130,BLANK131,BLANK132 , value
FROM CTE
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
WHERE value > 0.00
You cannot include MERCHANDISE_AMT here:
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)
AND in your final SELECT from the UNPIVOT results (4th column result set).
Including it in the IN list here means that you are unpivoting the value of this column into your row structure, so you can no longer select its value in your final SELECT.
So you need to pick. Do you want to unpivot the values in MERCHANDISE_AMT? If so, then leave it in the IN list of your UNPIVOT and remove it from final SELECT. If not, then remove it from your IN list and leave it in your final SELECT.
Seems like you would likely benefit from reading through the Microsoft examples on UNPIVOT.

Why isn't this CTE recognized?

I'm trying to pull in student majors to this sql by using a CTE, but when I try to add the CTE fields, or join the CTE with an implicit join, which works fine in other queries, oracle throws the error 'invalid identifier'. Any thoughts?
This is only the first part of many unions in this sql but I've seen examples where a CTE works fine with unions so I don't think thats it, and besides that when I run this code without the unions I get the same errors, 'invalid identifier'.
with major (pidm, major) as
(
select
a.sgbstdn_pidm,
a.sgbstdn_majr_code_1
from
sgbstdn a
where a.sgbstdn_term_code_eff = (select
max(b.sgbstdn_term_code_eff)
from
sgbstdn b
where
a.sgbstdn_pidm = b.sgbstdn_pidm
and b.sgbstdn_term_code_eff <= '202004'
and b.sgbstdn_term_code_eff > '202001')
)
select --authorized aid
spriden_id id
,spriden_last_name ||', '||spriden_first_name || ' '|| spriden_mi "Name"
,major.major "Major"
,rpratrm_fund_code "Fund"
,rpratrm_period "Period"
,rpratrm_offer_amt "Offer"
,rpratrm_accept_amt "Accept"
,null "Loan Net Orig Amt"
,RPRATRM_AUTHORIZE_AMT "Authorized"
,rpratrm_paid_amt "Paid"
,c.hr "Census Hours"
,r.hr "Enrolled Hours"
,c.con "Consortium"
,b.pbcode "P Budget Code"
,b.pbcode_locked "P Budget Code Locked?"
,b.b_locked "Budget Locked"
--,astd.astd "Academic Standing"
,s.sap "SAP Code"
,s.term "SAP Term"
,decode(h.pidm, null, 'No', 'Yes') "Holds"
,admit.admit "Admitted?"
from
spriden
,rpratrm
--,(select SGVSTDN_pidm pidm, sgvstdn_astd_desc astd from SGVSTDN where SGVSTDN_term_code = '202003') astd
--admitted?
,(select
sgbstdn_pidm pidm
,case
when sgbstdn_levl_code like 'N%' then 'No'
when sgbstdn_levl_code is null then 'No Student Record found this term'
else 'Yes'
end admit
from
sgbstdn
where
sgbstdn_term_code_eff = '202003') admit
--HOLDS
,(select
rorhold_pidm pidm
from
rorhold
where
to_char(sysdate, 'YYYYMMDD') <= to_char(RORHOLD_TO_DATE, 'YYYYMMDD')
and to_char(sysdate, 'YYYYMMDD') >= to_char(RORHOLD_FROM_DATE, 'YYYYMMDD')
) h
--SAP
,(select
a.rorsapr_pidm pidm
,a.rorsapr_term_code term
,a.rorsapr_sapr_code sap
from
rorsapr a
where
a.rorsapr_term_code = (select max(b.rorsapr_term_code) from rorsapr b where a.rorsapr_pidm = b.rorsapr_pidm and b.rorsapr_term_code <= '202003')) s
--Period Budget Code Lock/FREEZE
,(select
rbrapbg_pidm pidm
,RBRAPBG_PBGP_CODE pbcode
,decode(RBRAPBG_PBGP_CODE_LOCK_IND, 'Y', 'Yes', 'No') pbcode_locked
,decode(RBRAPBG_BUDGET_FREEZE_IND, 'Y', 'Yes', 'No') b_locked
from
rbrapbg
where
RBRAPBG_RUN_NAME = 'ACTUAL'
and RBRAPBG_PERIOD = '202003'
and RBRAPBG_AIDY_CODE = '2021') b
,(select
rorenrl_pidm pidm
,rorenrl_term_code term
,RORENRL_FINAID_ADJ_HR hr
,RORENRL_CONSORTIUM_IND con
from
rorenrl
where
rorenrl_enrr_code = 'STANDARD'
and rorenrl_term_code like '202003') c
,(select
sfrstcr_pidm pidm
,sfrstcr_term_code term
,sum(sfrstcr_credit_hr) hr
from
sfrstcr
where
sfrstcr_term_code like '202003'
and sfrstcr_rsts_code in (select stvrsts_code from stvrsts where STVRSTS_INCL_SECT_ENRL = 'Y')
group by sfrstcr_pidm, sfrstcr_term_code) r
where
spriden_change_ind is null
and spriden_pidm = rpratrm_pidm
and rpratrm_aidy_code = '2021'
and RPRATRM_AUTHORIZE_AMT is not null
and rpratrm_pidm = c.pidm(+)
and rpratrm_period = c.term(+)
and rpratrm_pidm = r.pidm(+)
and rpratrm_period = r.term(+)
and rpratrm_period = '202003'
and rpratrm_pidm = b.pidm(+)
and rpratrm_pidm = s.pidm(+)
and rpratrm_pidm = h.pidm(+)
and rpratrm_pidm = admit.pidm(+)
and rpratrm_pidm = major.pidm
--and rpratrm_pidm = astd.pidm(+)
and not exists (select 'asdf' from SGVSTDN a where a.sgvstdn_pidm = rpratrm_period and a.SGVSTDN_term_code = (select max(b.sgvstdn_term_code) from sgvstdn b where b.sgvstdn_term_code <= '202003' and b.sgvstdn_astd_desc is not null and a.sgvstdn_pidm = b.sgvstdn_pidm) and a.sgvstdn_astd_code = 'SU')
and (r.hr is not null or c.hr is not null)
and not exists (select 'afd' from rorstat where rorstat_pidm = rpratrm_pidm and rorstat_aidy_code = rpratrm_aidy_code and RORSTAT_DISB_REQ_COMP_DATE is null)
and not exists (select 'afd' from rrrareq where rrrareq_pidm = rpratrm_pidm and rrrareq_aidy_code = rpratrm_aidy_code and rrrareq_fund_code = rpratrm_fund_code and RRRAREQ_SAT_IND = 'N')
--this will exclude those without loans should be a loan only query. if chur is auth but mpn not done, student won't show up
and exists (select 'asdf' from rlrdlor, rlrdldb where RLRDLOR_PIDM = rlrdldb_pidm and RLRDLOR_PIDM = rpratrm_pidm and RLRDLOR_LOAN_NO = rlrdldb_loan_no and RLRDLOR_AIDY_CODE = rlrdldb_aidy_code
and rlrdlor_aidy_code = rpratrm_aidy_code and RLRDLOR_FUND_CODE = rlrdldb_fund_code and rlrdlor_fund_code = rpratrm_fund_code and RLRDLOR_MPN_LINKED_IND = 'Y')
Adding the CTE to the from clause made it work. Forgot about that little detail.

Wrap CTE inside another Select statement

Is it possible to wrap a CTE inside of another Select statement?
Here is my CTE:
WITH IRS AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'IRS' ) ,
PA AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'PA' )
SELECT IRS_WTHD.BUSINESS_UNIT, IRS_WTHD.VOUCHER_ID, IRS_WTHD.VOUCHER_LINE_NUM,
--COLUMN 1 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN 'PA'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'IRS'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'IRS'
ELSE ''
END ,
--COLUMN 2 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ','0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'MISC7'
WHEN PA_WTHD.WTHD_ENTITY = '' THEN ''
ELSE 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
END
FROM IRS IRS_WTHD
LEFT JOIN PA PA_WTHD ON PA_WTHD.BUSINESS_UNIT = IRS_WTHD.BUSINESS_UNIT AND PA_WTHD.VOUCHER_ID = IRS_WTHD.VOUCHER_ID AND PA_WTHD.VOUCHER_LINE_NUM = IRS_WTHD.VOUCHER_LINE_NUM
I would like to wrap the above CTE inside of this main SQL Select statement below and output the two CASE statement columns above into the final SELECT statement below while joining on BUSINESS_UNIT, VOUCHER_ID, and VOUCHER_LINE_NUM fields from the PS_VCHR_LINE_WTHD table :
--Main Select Statement:
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END, A.MERCHANDISE_AMT, B.QTY_VCHR, A.UNIT_PRICE, A.UNIT_OF_MEASURE, A.DESCR, A.PO_ID, A.LINE_NBR,
A.SCHED_NBR, B.PO_DIST_LINE_NUM, A.DESCR254_MIXED, '','',
F.OR_ENTITY + '.' + F.OR_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
ELSE '000' END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000000.' + '000000' ,'', C.ACCOUNTING_DT, '',
'','','', ISNULL(D.WTHD_ENTITY,''), '', '', '', A.SALETX_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
ORDER BY 1,2
Is this possible, or is there an alternate way of avoiding using the CTE? I am using the CTE because I need to be able to run Case statements across multiple rows and possibly return data on other rows.

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