SQL NOT EXISTS sub query not functioning as expected - sql
I have an issue where I am using a query to filter my results based on the lead time of an article. The confusing part for me is there is a sub section of that where i need to filter certain articles based on lead time and the country of origin. I am trying to do this using a NOT EXISTSstatement in side of WHERE but the results don't seem to be what I would expect. For example all articles with a country of origin of HONDURAS and a lead time of 90 should not return any results with a so_conf_del_date of after 2/15/19...however in the results I get many results of dates well into march which should be excluded from what I can see. Thought I would get a different set of eyes on it as I really don't use not exists a ton. thanks.
UPDATE: changing to NOT IN from NOT EXISTS and updated the correlation. Note also the subquery performs exactly as it should so not sure why I am getting results back outside of the range
Query UPDATED:
/* What to do about multiple COO's in ONE RANGE? ...join on order ORDER_ITEM.SEASONAL_INDICATOR? */
/* Use CASE WHEN in subquery to JOIN outerquery on vw_order_item.seasonal_indicator = OneRange_NAM.SEASON */
/* Assumption is being made that 'seasonal indicator' in vw_order_item would align with 'season' and thus COO in OneRange */
/* Added Date/LeadTime Parameters */
/* Use 'Planned Delivery Time'...this includes lead time and delivery time? */
/* Right join to ONE RANGE */
/* ARUN has no fully unallocated quantities - YES IT DOES */
/* 11/12/18 - replaced RDD with CDD */
SELECT kd.business_segment_desc,
q0.plant_code,
q0.req_cat AS 'requirement_category',
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus AS 'global status',
m.ib_lock,
o.country_of_origin
FROM pdx_sap_user..vw_mm_material m
JOIN pdx_sap_user..vw_kd_business_segment kd ON m.business_segment_code = kd.business_segment_code
JOIN asagdwpdx_prod..ArticleNumbers aa ON m.material = aa.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o ON m.material = o.article
AND aa.ArticleNumber = o.Article
JOIN
(SELECT i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
((i.open_quantity) - SUM(a.quantity)) AS 'allocated_quantity',
SUM(a.quantity) AS 'unallocated_quantity',
a.req_cat,
ROUND(SUM(a.quantity)/(i.open_quantity),2) AS 'percent_unallocated',
SUM(a.quantity) AS 'arun_allocated_qty',
CASE
WHEN i.seasonal_indicator = '18S'
THEN 'SS2018'
WHEN i.seasonal_indicator = '18F'
THEN 'FW2018'
WHEN i.seasonal_indicator = '19S'
THEN 'SS2019'
WHEN i.seasonal_indicator = '19F'
THEN 'FW2019'
ELSE 'NO SEASON'
END AS 'seasonal_indicator'
FROM pdx_sap_user..vw_order_item i
JOIN pdx_sap_user..vw_order_header h ON i.sales_order_number = h.sales_order_number
JOIN pdx_sap_user..vw_arun_norm_new a ON i.sales_order_number = a.sales_order_number
AND i.sales_order_item_number = a.sales_order_item_number
WHERE i.open_quantity > 0
AND h.commission_code_id = 'B'
AND a.stock_type = 'A'
GROUP BY i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
a.req_cat,
i.unallocated_quantity,
i.seasonal_indicator
HAVING SUM((a.quantity)/i.open_quantity) > .5) q0 ON m.material = q0.material
AND q0.seasonal_indicator = o.season
WHERE aa.LeadTime = '30'
AND q0.so_conf_del_date < '01/15/2019'
OR aa.LeadTime = '45'
AND q0.so_conf_del_date < '02/01/2019'
OR aa.LeadTime = '60'
AND q0.so_conf_del_date < '02/15/2019'
OR aa.LeadTime = '75'
AND q0.so_conf_del_date < '03/01/2019'
OR aa.LeadTime = '90'
AND q0.so_conf_del_date < '03/15/2019'
OR aa.LeadTime = '105'
AND q0.so_conf_del_date < '04/01/2019'
OR aa.LeadTime = '120'
AND q0.so_conf_del_date < '04/15/2019'
OR aa.LeadTime = '135'
AND q0.so_conf_del_date < '05/01/2019'
AND q0.sales_order_number NOT IN ( SELECT q01.sales_order_number
FROM pdx_sap_user..vw_order_item q01
JOIN pdx_sap_user..vw_arun_norm_new a1 ON q01.sales_order_number = a1.sales_order_number
AND q01.sales_order_item_number = a1.sales_order_item_number
JOIN asagdwpdx_prod..ArticleNumbers aa1 ON q01.material = aa1.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o1 ON q01.material = o1.article
WHERE
(
aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
)
OR
(
aa1.LeadTime = '45'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/01/2019'
)
OR
(
aa1.LeadTime = '60'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/15/2019'
)
OR
(
aa1.LeadTime = '75'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/01/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/15/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/01/2019'
)
OR
(
aa1.LeadTime = '105'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/15/2019'
)
AND q0.sales_order_number = q01.sales_order_number
AND aa.LeadTime = aa1.LeadTime
AND q0.so_conf_del_date = a1.so_conf_del_date
AND o.Country_of_Origin = o1.Country_of_Origin)
GROUP BY kd.business_segment_desc,
q0.plant_code,
q0.req_cat,
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus,
m.ib_lock,
o.country_of_origin
ORDER BY q0.sales_order_number DESC;
WORKING VERSION:
/* What to do about multiple COO's in ONE RANGE? ...join on order ORDER_ITEM.SEASONAL_INDICATOR? */
/* Use CASE WHEN in subquery to JOIN outerquery on vw_order_item.seasonal_indicator = OneRange_NAM.SEASON */
/* Assumption is being made that 'seasonal indicator' in vw_order_item would align with 'season' and thus COO in OneRange */
/* Added Date/LeadTime Parameters */
/* Use 'Planned Delivery Time'...this includes lead time and delivery time? */
/* Right join to ONE RANGE */
/* ARUN has no fully unallocated quantities - YES IT DOES */
/* 11/12/18 - replaced RDD with CDD */
SELECT kd.business_segment_desc,
q0.plant_code,
q0.req_cat AS 'requirement_category',
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus AS 'global status',
m.ib_lock,
o.country_of_origin
FROM pdx_sap_user..vw_mm_material m
JOIN pdx_sap_user..vw_kd_business_segment kd ON m.business_segment_code = kd.business_segment_code
JOIN asagdwpdx_prod..ArticleNumbers aa ON m.material = aa.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o ON m.material = o.article
AND aa.ArticleNumber = o.Article
JOIN
(SELECT i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
((i.open_quantity) - SUM(a.quantity)) AS 'allocated_quantity',
SUM(a.quantity) AS 'unallocated_quantity',
a.req_cat,
ROUND(SUM(a.quantity)/(i.open_quantity),2) AS 'percent_unallocated',
SUM(a.quantity) AS 'arun_allocated_qty',
CASE
WHEN i.seasonal_indicator = '18S'
THEN 'SS2018'
WHEN i.seasonal_indicator = '18F'
THEN 'FW2018'
WHEN i.seasonal_indicator = '19S'
THEN 'SS2019'
WHEN i.seasonal_indicator = '19F'
THEN 'FW2019'
ELSE 'NO SEASON'
END AS 'seasonal_indicator'
FROM pdx_sap_user..vw_order_item i
JOIN pdx_sap_user..vw_order_header h ON i.sales_order_number = h.sales_order_number
JOIN pdx_sap_user..vw_arun_norm_new a ON i.sales_order_number = a.sales_order_number
AND i.sales_order_item_number = a.sales_order_item_number
WHERE i.open_quantity > 0
AND h.commission_code_id = 'B'
AND a.stock_type = 'A'
AND i.sales_order_number NOT IN (SELECT q01.sales_order_number
FROM pdx_sap_user..vw_order_item q01
JOIN pdx_sap_user..vw_arun_norm_new a1 ON q01.sales_order_number = a1.sales_order_number
AND q01.sales_order_item_number = a1.sales_order_item_number
JOIN asagdwpdx_prod..ArticleNumbers aa1 ON q01.material = aa1.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o1 ON q01.material = o1.article
WHERE
(
aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
)
OR
(
aa1.LeadTime = '45'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/01/2019'
)
OR
(
aa1.LeadTime = '60'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/15/2019'
)
OR
(
aa1.LeadTime = '75'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/01/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/15/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/01/2019'
)
OR
(
aa1.LeadTime = '105'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/15/2019'
)
AND q01.sales_order_number = i.sales_order_number)
GROUP BY i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
a.req_cat,
i.unallocated_quantity,
i.seasonal_indicator
HAVING SUM((a.quantity)/i.open_quantity) > .5) q0 ON m.material = q0.material
AND q0.seasonal_indicator = o.season
WHERE aa.LeadTime = '30'
AND q0.so_conf_del_date < '01/15/2019'
OR aa.LeadTime = '45'
AND q0.so_conf_del_date < '02/01/2019'
OR aa.LeadTime = '60'
AND q0.so_conf_del_date < '02/15/2019'
OR aa.LeadTime = '75'
AND q0.so_conf_del_date < '03/01/2019'
OR aa.LeadTime = '90'
AND q0.so_conf_del_date < '03/15/2019'
OR aa.LeadTime = '105'
AND q0.so_conf_del_date < '04/01/2019'
OR aa.LeadTime = '120'
AND q0.so_conf_del_date < '04/15/2019'
OR aa.LeadTime = '135'
AND q0.so_conf_del_date < '05/01/2019'
GROUP BY kd.business_segment_desc,
q0.plant_code,
q0.req_cat,
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus,
m.ib_lock,
o.country_of_origin
ORDER BY q0.sales_order_number DESC
Your OR is short circuiting. For example, look at this piece:
SELECT *
FROM Table
WHERE aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
OR aa1.LeadTime = '45'
Returns all records with aa1.LeadTime = '45' regardless of the other conditions.
I guess you mean this:
WHERE
(
aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
)
OR
(
aa1.LeadTime = '45'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/01/2019'
)
OR
(
aa1.LeadTime = '60'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/15/2019'
)
....
....
which is a very different expression.
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.
Getting Error Ora-1489: Concatenated string is too long when I use LISTAGG
Here is the Sql. I am trying to use XMLAGG. SELECT distinct LEARN_OBS_LCODE "KEY", 'Results' "TEMPLATE", 'en-US' "LOCALE", 'html' OUTPUT_FORMAT, 'TTX Checklist Activity Notification' "OUTPUT_NAME", 'EMAIL' DEL_CHANNEL, LEARN_OBS_EMAIL "PARAMETER1", -- "PARAMETER2", 'ejjc.fa.sender#workflow.mail.us6.oraclecloud.com' "PARAMETER3", '(' || LEARN_OBS_LNAME || ') ' || 'Observation Checklist Pending' || ' - ' || To_char(sysdate, 'MM/DD/YYYY') "PARAMETER4", 'true' "PARAMETER6" FROM (select DISTINCT rtrim(LOCT.internal_location_code) LEARN_OBS_LCODE, rtrim(LOC.location_name) LEARN_OBS_LNAME, listagg((PEA.EMAIL_ADDRESS || ','|| LOBS.EMAIL1), ',') within group (order by LOCT.internal_location_code) LEARN_OBS_EMAIL --XMLAGG(XMLAGG(XMLELEMENT(E,PEA.EMAIL_ADDRESS|| ','|| LOBS.EMAIL1 || ',')).extract('//text()') order by LOCT.internal_location_code).getClobaVal() as LEARN_OBS_EMAIL FROM fusion.per_all_people_f PAPF INNER JOIN fusion.per_person_names_f PER ON PAPF.person_id = PER.person_id AND Trunc(sysdate) BETWEEN PER.effective_start_date AND PER.effective_end_date AND PER.name_type = 'GLOBAL' LEFT JOIN FUSION.PER_USERS PLU ON PLU.PERSON_ID = PAPF.PERSON_ID AND Trunc(sysdate) BETWEEN PLU.START_DATE AND NVL(PLU.END_DATE,Trunc(sysdate)) AND PLU.ACTIVE_FLAG = 'Y' --AND PLU.USERNAME = FND_GLOBAL.USER_NAME LEFT JOIN FUSION.PER_USER_ROLES PUR ON PUR.USER_ID = PLU.USER_ID AND Trunc(sysdate) BETWEEN PUR.START_DATE AND NVL(PUR.END_DATE, Trunc(sysdate)) LEFT JOIN FUSION.PER_ROLES_DN PR_BASE ON PR_BASE.ROLE_ID = PUR.ROLE_ID LEFT JOIN FUSION.PER_ROLES_DN_TL PLR ON PLR.ROLE_ID = PR_BASE.ROLE_ID AND PLR.LANGUAGE = USERENV('LANG') AND PLR.ROLE_NAME IS NOT NULL INNER JOIN fusion.per_all_assignments_f ASG ON ASG.person_id = PAPF.person_id AND Trunc(sysdate) BETWEEN ASG.effective_start_date AND ASG.effective_end_date AND ASG.primary_flag = 'Y' AND ASG.assignment_type IN ( 'E', 'C','N' ) AND ASG.effective_latest_change = 'Y' AND ASG.assignment_status_type <> 'INACTIVE' LEFT JOIN per_location_details_f_vl LOC ON ASG.location_id = LOC.location_id AND Trunc(sysdate) BETWEEN LOC.effective_start_date AND LOC.effective_end_date LEFT JOIN per_locations LOCT ON LOC.location_id = LOCT.location_id LEFT JOIN fusion.per_email_addresses PEA ON PEA.person_id = PAPF.person_id AND Trunc(sysdate) BETWEEN PEA.date_from AND Nvl(PEA.date_to, Trunc( sysdate)) AND PEA.email_type = 'W1' inner JOIN LEARN_OBSERVER LOBS ON ASG.LOCATION_ID = LOBS.LOCATION_ID WHERE Trunc(sysdate) BETWEEN PAPF.effective_start_date AND PAPF.effective_end_date --and papf.person_number = '38148' AND UPPER(PR_BASE.ROLE_COMMON_NAME) = 'TTX_LEARNING_OBSERVER_BY_LOCATION_DATA' --AND UPPER(PLR.ROLE_NAME) = 'TTX LEARNING OBSERVER BY LOCATION' GROUP BY LOCT.internal_location_code , LOC.location_name
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.
Can someone show me how to add these fields to this Stored Procedure
I have a SP that was built for us that does a summary statement of tables in our DB. What I am trying to do is make it so the SP also pulls that last year/month of data as well based on the date entered. Below is the SQL code I am working with. What I am trying to get is a total and Volume field that is the sum based on the date parameter entered minus 1 month. For example: If I put in 2013 10 01 start and 2013 10 31 end I would get the total and volume for 2013-10-01 to 2013-10-31 and in 2 separate columns the total and volume for 2013-09-01 to 1013-09-30 Code ( #Start DATETIME, #End DATETIME ) AS DECLARE #reference int, #sSQL VARCHAR(2000) BEGIN select Convert(datetime,Cast(edi.Creation_dt as varchar(8)),103) as Date, ia.xref_no_tx, la.ldc_acct_no, la.serv_loc_nm , a.acct_nm, c.company_last_nm , Case RG.Rate_cd When 'DLS' then 'HEDGE' When 'STL' then 'STL' WHen 'SPOT BILLING' then 'SPOT' WHen 'SL SPOT' then 'STL SPOT' Else null End as Acct_type , Convert(datetime,Cast(ia.start_dt as varchar(8)),103)as Start_dt , Convert(datetime,Cast(ia.end_dt as varchar(8)),103) as End_dt , edi.trans_sub_ty as Inv_type , max( case when la.class_ty_cd = 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'FEES' then th.trans_qty when la.class_ty_cd = 'MUNI' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'EXCS' then th.trans_qty when la.class_ty_cd <> 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'BASE' then th.trans_qty else 0 end) as Volume , sum(th.trans_am) as Total from invoice_advise_relate iar, transaction_history th ,invoice_advise ia, ldc_account la, account a, customer c, edi_transaction edi , (select max(edi_trans_id) as m_edi_trans, relate_id from edi_transaction where class_nm = 'cInvoiceAdvise' group by relate_id) as edic , (Select max(rating_group_id) as m_rate, ldc_acct_id from rating_group group by ldc_acct_Id) as C_Rate , rating_group rg where iar.trans_id = th.trans_id and th.cancel_in = 'N' and th.trans_ty_cd not in ('PAY', 'ANC') and iar.inv_adv_id = ia.inv_adv_id and ia.ldc_acct_id = la.ldc_acct_id and la.acct_id = a.acct_id and a.cust_id = c.cust_id and la.ldc_acct_no not like 'E%' and edi.Creation_dt >= convert(varchar,#Start,112) and edi.Creation_dt <= convert(varchar,#End,112) and edi.relate_id = ia.inv_adv_id and edic.m_edi_trans = edi.edi_trans_id and edi.response_cd = '' and rg.rating_group_id = C_Rate.M_Rate and C_Rate.LDC_Acct_Id = la.ldc_Acct_Id and edi.trans_sub_ty <> '00' group by edi.Creation_dt, ia.xref_no_tx, la.ldc_acct_no,la.serv_loc_nm, a.acct_nm, c.company_last_nm, ia.start_dt, ia.end_dt,edi.trans_sub_ty, rg.rate_cd
Start off by declaring and initializing a start date for the previous month. DECLARE #PrevStart datetime SELECT #PrevStart = dateadd(month, -1, #Start) In your WHERE clause substitute the previous start date for start date so that you include last month's data as well as this month's. and edi.Creation_dt >= convert(varchar,#PrevStart,112) and edi.Creation_dt <= convert(varchar,#End,112) Then you filter last month's data from this month's using CASE statement logic. , max( case when la.class_ty_cd = 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'FEES' AND edi.Creation_dt >= convert(varchar,#Start,112) then th.trans_qty when la.class_ty_cd = 'MUNI' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'EXCS' AND edi.Creation_dt >= convert(varchar,#Start,112) then th.trans_qty when la.class_ty_cd <> 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'BASE' AND edi.Creation_dt >= convert(varchar,#Start,112) then th.trans_qty else 0 end) as Volume , sum(CASE WHEN edi.Creation_dt >= convert(varchar,#Start,112) THEN th.trans_am ELSE 0 END) as Total , max( case when la.class_ty_cd = 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'FEES' AND edi.Creation_dt < convert(varchar,#Start,112) then th.trans_qty when la.class_ty_cd = 'MUNI' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'EXCS' AND edi.Creation_dt < convert(varchar,#Start,112) then th.trans_qty when la.class_ty_cd <> 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'BASE' AND edi.Creation_dt < convert(varchar,#Start,112) then th.trans_qty else 0 end) as PrevVolume , sum(CASE WHEN edi.Creation_dt < convert(varchar,#Start,112) THEN th.trans_am ELSE 0 END) as PrevTotal
Could use some pointers to create dat file from sql query
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.