Count results generated by case statement - sql

I'm working on a query that analyzes two records and checks whether one record matches the second record. If record 1 column matches record 2 column then there's no error. If record 1 column does not match record 2 column then there's an error. I want to be able to count the errors per YPID. For the life of me... I can't figure it out. Help!
Here's my query:
select r1.ypid, r1.business_name as Base_Listed_Name, r1.street_address as Base_Listed_Address, r1.city as Base_Listed_City, r1.state as Base_Listed_State, r1.zip5 as Base_Listed_Zip, rmve1.value as Base_URL,
r2.business_name as Google_Scanned_Listed_Name, r2.street_address as Google_Scanned_Listed_Address, r2.city as Google_Scanned_Listed_City, r2.state as Google_Scanned_Listed_City, r2.zip5 as Google_Scanned_Listed_Zip, rmve2.value as Google_Scanned_URL,
ls.presence_score, ls.listing_score,
case
when r1.business_name = r2.business_name then 'no_error'
else 'error'
end Business_Name_Status,
case
when r1.latitude = r2.latitude then 'no_error'
when r1.longitude = r2.longitude then 'no_error'
when r1.latitude is null or r1.latitude in ('0') then (case when r1.street_address = r2.street_address then 'no_error' else 'error' end)
else 'error'
end Street_Address_Status,
case
when r1.city = r2.city then 'no_error'
else 'error'
end City_Status,
case
when r1.state = r2.state then 'no_error'
else 'error'
end State_Status,
case
when r1.zip5 = r2.zip5 then 'no_error'
else 'error'
end Zip_Status,
case
when lower(replace(replace(replace(replace(replace(replace(rmve1.value, 'http://www.', null), 'www.', null), 'https://www.', null), 'http://', null), 'https://', null), 'wwww.', null))
= lower(replace(replace(replace(replace(replace(replace(rmve2.value, 'http://www.', null), 'www.', null), 'https://www.', null), 'http://', null), 'https://', null), 'wwww.', null)) then 'no_error'
else 'error'
end URL_Status
from mdm2.records r1 join mdm2.records r2 on r1.ypid = r2.ypid join mdm2.presence_listing_statuses ls on r1.ypid = ls.ypid
left outer join mdm2.record_mult_val_exts rmve1 on r1.id = rmve1.record_id and rmve1.extension_type = 'urls' and rmve1.value_type = 'primary'
left outer join mdm2.record_mult_val_exts rmve2 on r2.id = rmve2.record_id and rmve2.extension_type = 'urls' and rmve2.value_type = 'primary'
where r1.ypid in ('5625222','13846403','21974776','22806234','30303664','453728041')
and r1.source_code = 'PPA'
and r2.source_code = 'GOOG';
results
|YPID|BASE_LISTED_NAME|BASE_LISTED_ADDRESS|BASE_LISTED_CITY|BASE_LISTED_STATE|BASE_LISTED_ZIP|BASE_URL|GOOGLE_SCANNED_LISTED_NAME|GOOGLE_SCANNED_LISTED_ADDRESS|GOOGLE_SCANNED_LISTED_CITY|GOOGLE_SCANNED_LISTED_CITY_1|GOOGLE_SCANNED_LISTED_ZIP|GOOGLE_SCANNED_URL|PRESENCE_SCORE|LISTING_SCORE|BUSINESS_NAME_STATUS|STREET_ADDRESS_STATUS|CITY_STATUS|STATE_STATUS|ZIP_STATUS|URL_STATUS|
|5625222|Affinity Insurance Agency|5702 S Staples St Suite G|Corpus Christi|TX|78413|http://affinityia.com|Affinity Insurance Agency|5702 S Staples St Suite G|Corpus Christi|TX|78413|http://corpuschristiinsuranceprovider.com|90|97|no_error|no_error|no_error|no_error|no_error|error|
|13846403|Party Bazaar|4435 Lovers Ln|Dallas|TX|75225|www.partybazaardallas.com|Party Bazaar|4435 Lovers Ln|Dallas|TX|75225|http://partybazaardallas.com|93|100|no_error|no_error|no_error|no_error|no_error|no_error|
|21974776|Alterations To Go|2100 Arden Way Ste 150|Sacramento|CA|95825|http://www.alterationstogosacramento.com|Alterations To Go|2100 Arden Way # 150|Sacramento|CA|95825|http://alterations-togo.com|91|99|no_error|no_error|no_error|no_error|no_error|error|
|22806234|RV America|3640 Chambers Rd|Aurora|CO|80011|http://www.rvamericainc.com/pages/rv%20financing|RV America|3640 Chambers Rd|Aurora|CO|80011|http://rvamericainc.com|83|91|no_error|no_error|no_error|no_error|no_error|error|
|30303664|Sorelli Hair Studio & Spa|400 Saint Andrews Blvd|Melbourne|FL|32940|http://sorellihairstudio.com|Sorelli Hair Studio & Spa|400 Saint Andrews Blvd|Melbourne|FL|32940|http://sorellihairstudio.com|91|99|no_error|no_error|no_error|no_error|no_error|no_error|
|453728041|Carolina Driving School|534 Walkertown Guthrie Rd|Winston Salem|NC|27101|http://www.carolinadriving.com|Carolina Driving School|534 Walkertown Guthrie Rd|Winston Salem|NC|27101|http://carolinadrivingschool.com|87|97|no_error|no_error|no_error|no_error|no_error|error|

i guess you need to use LEAD , LAG function .
check this link http://oracle-base.com/articles/misc/lag-lead-analytic-functions.php
LAG function is used to access data from a previous row
LEAD function is used to return data from the next row.
by this you can compare 1st row with 2nd row

Related

Do I need to the field I am creating in the case statement in select statement?

Figured it out! I had quotes around the 'FulFillment Method' after the 'end as' part of the case expression. Once I removed the quotes it ran!
I am getting this error when I run the below code:
Error in SQL statement: ParseException:
mismatched input ''FulFillmentMethod'' expecting {, ';'}(line 45, pos 14)
This error started to occur after adding the case statement to the query. Prior to adding the case statement, everything ran perfectly fine.
Do I need to add FulFillment method to the select statement?
create or replace view bu_XXXX.X_Seasonal as
SELECT
daily.StoreNumber,
daily.ChannelNetOriginated,
FlexFulFillmentSubtype,
SalesDollar,
SalesUnit,
ClearSalesDollar,
ClearSalesUnit,
PromoSalesDollar,
PromoSalesUnit,
RegularSalesDollar,
RegularSalesUnit,
Date,
DateYear,
DateYearMonth,
Week,
item.ItemNumber,
item.Department,
item.Class,
item.Subclass,
item.HSY_Brand,
item.HSY_Manufacturer,
item.Style,
item.ItemDescription,
item.X_DPCI_and_Description AS Item,
item.X_DPCI,
item.DPCI,
item.HSY_Subsegment,
Store.Region,
Store.Zipcode,
Store.State_Name as State,
Store.Store_ABBR as StoreFormat,
Store.CMSC_F,
Store.LocationType,
CASE
WHEN( daily.ChannelNetOriginated = 'DC') THEN Store.LocationType
WHEN( daily.StoreNumber in ('3134','3991')) THEN 'DIRECT VENDOR SHIP'
WHEN (Store.CMSC_F = 'FC STORE' )THEN 'FULFILLMENT CENTER'
WHEN ((daily.ChannelNetOriginated = 'ONLINE' AND FlexFulFillmentSubtype in ('SHIP FROM STORE', 'SHIP TO STORE', 'SHIPT', 'STORE PICK-UP'))) THEN 'FLEXIBLE FULFILLMENT'
WHEN ((daily.ChannelNetOriginated = 'STORE' AND Store.CMSC_F in ('SUPER TARGET', 'P FRESH', 'EXPRESS TARGET', 'CITY TARGET', 'GENERAL MERCHANDISING'))) THEN 'STORE'
ELSE 'NA'
END as FulFillmentMethod
FROM
std_X.dailydata daily
LEFT JOIN std_X.items item
ON daily.ItemNumber = item.ItemNumber
AND daily.VendorNumber = item.VendorNumber
INNER JOIN std_X.stores Store
ON daily.StoreNumber = Store.StoreNumber
and DateYear <> '2018'
Shouldn't conditions be like this?
WHEN
(
(daily.ChannelNetOriginated = 'ONLINE'
AND FlexFulFillmentSubtype in ('SHIP FROM STORE', 'SHIP TO STORE', 'SHIPT', 'STORE PICK-UP')
)
)
THEN 'FLEXIBLE FULFILLMENT'
WHEN (
(daily.ChannelNetOriginated = 'STORE'
AND Store.CMSC_F in ('SUPER', 'EXPRESS', 'CITY', 'GENERAL MERCHANDISING')
)
)
THEN 'STORE'

SQL Update query with condition

Is it better that I just use the where for update query with conditions or there is a better way to do?
Below is a sample of my SQL query which I wanted to update if the Order_ID = 10 plus payment_check is N or response_msg is null, kindly correct me if my query is wrong.
UPDATE dbo.sample1
SET Payment_Generated = 'Y',
Transaction_ID = '123',
Response_Msg = 'ok',
Response_Code = '1',
Created_on = '2020-05-29T11:29:30'
WHERE Order_ID = '10' and Payment_Check = 'N' or Response_Code IS NULL
Expected Result if the payment_check is N or response_code is null
Payment_Generated = 'Y',
Transaction_ID = '123',
Response_Msg = 'ok',
Response_Code = '1',
Created_on = '2020-05-29T11:29:30'
Order_ID = '10'
Payment_Check = 'N'

How to query Oracle grouping?

I have such a problem and I don't know how to solve it, can you help me? t
The query returns a result that is shown on the photo and I want to get it to be shown in one line instead of many based on type of age.
https://imgur.com/a/OA6CBpa
with x as (
select ai.invoice_id, ai.invoice_num, ai.invoice_amount, ai.amount_paid,
trial.entity_id, trial.acctd_amount, trial.entered_amount, trial.gl_date,
aps.amount_remaining, aps.gross_amount, aps.due_date, aps.payment_status_flag,
trial.gl_date - aps.due_date dni_opoznienia
from ap_invoices_all ai,
xla.xla_transaction_entities xte,
(
select nvl (tr.applied_to_entity_id, tr.source_entity_id) entity_id,
tr.source_application_id application_id,
sum (nvl (tr.acctd_unrounded_cr, 0)) - sum (nvl (tr.acctd_unrounded_dr, 0)) acctd_amount,
sum (nvl (tr.entered_unrounded_cr, 0)) - sum (nvl (tr.entered_unrounded_dr, 0)) entered_amount,
max(tr.gl_date) gl_date
from xla.xla_trial_balances tr
where 1=1
and tr.definition_code = 'AP_200_1001'
and tr.source_application_id = 200
and tr.gl_date <= fnd_date.canonical_to_date('2019-12-13') -- Data KG
group by nvl (tr.applied_to_entity_id, tr.source_entity_id),
tr.source_application_id
) trial,
ap_payment_schedules_all aps
where 1=1
and ai.invoice_id = 3568325
and nvl(xte.source_id_int_1, -99) = ai.invoice_id
and xte.ledger_id = 1001
and xte.entity_code = 'AP_INVOICES'
and xte.entity_id = trial.entity_id
and xte.application_id = trial.application_id
and ai.invoice_id = aps.invoice_id
)
select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date,
x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag,
x.dni_opoznienia, aapl.days_start, aapl.days_to,
case
when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount
else 0
end przedzial
from x,
ap_aging_periods aap,
ap_aging_period_lines aapl
where 1=1
and aap.period_name = 'TEST 5 okresow'
and aap.aging_period_id = aapl.aging_period_id
Based on your comment I guess you need the below
select * from (select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date,
x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag,
x.dni_opoznienia, aapl.days_start, aapl.days_to,
case
when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount
else 0
end przedzial
from x,
ap_aging_periods aap,
ap_aging_period_lines aapl
where 1=1
and aap.period_name = 'TEST 5 okresow'
and aap.aging_period_id = aapl.aging_period_id)
where przedzial > 0;

Error "ORA-00936: missing expression" for below SQL statement

Please help to check why below SQL statement got error of "ORA-00936: missing expression" when executed on Oracle 11g R2.
select part.*,
decode(pv.dspuom, null, part.untqty, part.untqty / prtftp_dtl.untqty) dsp_untqty,
decode(pv.dspuom, null, pv.stkuom, pv.dspuom) untqty_uom,
decode(pv.dspuom, null, cast(null as int), pv.stkuom, cast(null as int), mod(part.untqty, prtftp_dtl.untqty)) rem_untqty,
decode(pv.dspuom, null, null, pv.stkuom, null, pv.stkuom) rem_untqty_uom
from (select #select_on:raw sum(untqty) untqty,
sum(catch_qty) catch_qty,
invadj.prtnum fixed_prtnum,
invadj.prt_client_id fixed_prt_client_id,
invadj.wh_id fixed_wh_id,
invadj.play_prc_id
from invadj
where exists(select 'x'
from prtmst_view
where prtmst_view.prtnum = invadj.prtnum
and prtmst_view.prt_client_id = invadj.prt_client_id
and prtmst_view.wh_id = invadj.wh_id
and prtmst_view.prdflg = 1)
and #+moddte:date
and #+invadj.play_prc_id
and #+invadj.prtnum
and #+invadj.prt_client_id
and wh_id = #wh_id
and #*
group by #result_string:raw,
invadj.prtnum,
invadj.prt_client_id,
invadj.wh_id,
invadj.play_prc_id
having sum(untqty) <> 0
or sum(catch_qty) <> 0) part left
join prtmst_view pv
on pv.prtnum = part.fixed_prtnum
and pv.prt_client_id = part.fixed_prt_client_id
and pv.wh_id = part.fixed_wh_id left
join prtftp
on prtftp.prtnum = pv.prtnum
and prtftp.prt_client_id = pv.prt_client_id
and prtftp.wh_id = pv.wh_id
and prtftp.defftp_flg = 1 left
join prtftp_dtl
on prtftp.prtnum = prtftp_dtl.prtnum
and prtftp.ftpcod = prtftp_dtl.ftpcod
and prtftp.prt_client_id = prtftp_dtl.prt_client_id
and prtftp.wh_id = prtftp_dtl.wh_id
and prtftp_dtl.uomcod = nvl(pv.dspuom, pv.stkuom)
I think the syntax may be off a bit.
Look at this line below
FROM (SELECT # select_on:raw sum(untqty) untqty,
The # character seems odd

Improve select statement performance

I'm with an Select performance issue, how can I make this SQL more efficient?
SELECT
O.DT_OCORRENCIA,
S.NU_SMP,
CLI.NM_APELIDO CLI,
TRANS.NM_ENTIDADE TRANS,
TPO.DS_TIPO_OCORRENCIA,
O.DS_OCORRENCIA,
REPLACE(FNC_RETORNA_MOTORISTAS(S.CD_SMP), '<br>', ';') AS NOME_MOTORISTA,
OG.DS_NOME AS DS_NOME_ORIGEM,
DG.DS_NOME AS DS_NOME_DESTINO,
U.NM_LOGIN AS DS_USUARIO_OCORRENCIA,
CASE
WHEN O.CD_USUARIO_INFORMOU = 717 THEN
'NAO'
ELSE
'SIM'
END FL_MANUAL,
CASE
WHEN (O.FL_ENVIOU_EMAIL_CLIENTE = 'S' OR O.FL_ENVIOU_EMAIL_TRANSP = 'S') THEN
'SIM'
ELSE
'NÃO'
END ENVIOU_EMAIL,
DECODE(O.NU_LOCAL_OCORRENCIA,
'1',
'Origem',
'2',
'Em transito',
'3',
'Alvos',
'4',
'Indiferente') DS_LOCAL_OCORRENCIA,
TOPER.DS_TIPO_OPERACAO
FROM TB_SMP S
INNER JOIN TB_OCORRENCIA O
ON O.CD_SMP = S.CD_SMP
INNER JOIN TB_TIPO_OCORRENCIA TPO
ON O.CD_TIPO_OCORRENCIA = TPO.CD_TIPO_OCORRENCIA
LEFT JOIN TB_TIPO_OPERACAO TOPER
ON TOPER.CD_TIPO_OPERACAO = S.CD_TIPO_OPERACAO
LEFT JOIN TB_USUARIO U
ON U.CD_USUARIO = O.CD_USUARIO_INFORMOU
LEFT JOIN TB_ENTIDADE CLI
ON CLI.CD_ENTIDADE = S.CD_ENTIDADE_CLIENTE
LEFT JOIN TB_ENTIDADE TRANS
ON TRANS.CD_ENTIDADE = S.CD_ENTIDADE_TRANSPORTADOR
LEFT JOIN TB_PONTO_GEOREFERENCIADO OG
ON OG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_ORIGEM
LEFT JOIN TB_PONTO_GEOREFERENCIADO DG
ON (S.CD_PONTO_GEO_DESTINO IS NULL AND
DG.CD_PONTO_GEOREFERENCIADO =
FNC_GET_ULTIMA_ENTREGA_PONTO(S.CD_SMP))
OR (S.CD_PONTO_GEO_DESTINO IS NOT NULL AND
DG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_DESTINO)
WHERE EXISTS (SELECT 1
FROM TB_TIPO_OCORRENCIA T
WHERE T.CD_TIPO_OCORRENCIA = O.CD_TIPO_OCORRENCIA)
AND S.DT_CADASTRO BETWEEN to_date('21/04/2014', 'dd/MM/yyyy') AND to_date('09/06/2014', 'dd/MM/yyyy')
AND O.DT_OCORRENCIA BETWEEN to_date('10/05/2014','dd/MM/yyyy') AND to_date('20/05/2014','dd/MM/yyyy')
AND S.cd_tipo_operacao in
(-1, 27, 11, 13, 37, 6, 7, 21, 12, 36, 28, 4, 5)
-- order by using linq?
ORDER BY CLI.NM_APELIDO,
TRANS.NM_APELIDO,
O.DT_OCORRENCIA,
DS_TIPO_OCORRENCIA
Here goes my execution plan:
PS.: I don't know nothing about sql tunnig :(
You can move some of the WHERE conditions to the JOIN conditions as you are doing an INNER JOIN on these tables, as below. Then, you would be operating on a smaller data set when you come to the LEFT JOIN conditions.
SELECT
O.DT_OCORRENCIA,
S.NU_SMP,
CLI.NM_APELIDO CLI,
TRANS.NM_ENTIDADE TRANS,
TPO.DS_TIPO_OCORRENCIA,
O.DS_OCORRENCIA,
REPLACE(FNC_RETORNA_MOTORISTAS(S.CD_SMP), '<br>', ';') AS NOME_MOTORISTA,
OG.DS_NOME AS DS_NOME_ORIGEM,
DG.DS_NOME AS DS_NOME_DESTINO,
U.NM_LOGIN AS DS_USUARIO_OCORRENCIA,
CASE
WHEN O.CD_USUARIO_INFORMOU = 717 THEN
'NAO'
ELSE
'SIM'
END FL_MANUAL,
CASE
WHEN (O.FL_ENVIOU_EMAIL_CLIENTE = 'S' OR O.FL_ENVIOU_EMAIL_TRANSP = 'S') THEN
'SIM'
ELSE
'NÃO'
END ENVIOU_EMAIL,
DECODE(O.NU_LOCAL_OCORRENCIA,
'1',
'Origem',
'2',
'Em transito',
'3',
'Alvos',
'4',
'Indiferente') DS_LOCAL_OCORRENCIA,
TOPER.DS_TIPO_OPERACAO
FROM TB_SMP S
INNER JOIN TB_OCORRENCIA O
ON O.CD_SMP = S.CD_SMP
AND S.DT_CADASTRO BETWEEN to_date('21/04/2014', 'dd/MM/yyyy') AND to_date('09/06/2014', 'dd/MM/yyyy')
AND O.DT_OCORRENCIA BETWEEN to_date('10/05/2014','dd/MM/yyyy') AND to_date('20/05/2014','dd/MM/yyyy')
AND S.cd_tipo_operacao in
(-1, 27, 11, 13, 37, 6, 7, 21, 12, 36, 28, 4, 5)
INNER JOIN TB_TIPO_OCORRENCIA TPO
ON O.CD_TIPO_OCORRENCIA = TPO.CD_TIPO_OCORRENCIA
LEFT JOIN TB_TIPO_OPERACAO TOPER
ON TOPER.CD_TIPO_OPERACAO = S.CD_TIPO_OPERACAO
LEFT JOIN TB_USUARIO U
ON U.CD_USUARIO = O.CD_USUARIO_INFORMOU
LEFT JOIN TB_ENTIDADE CLI
ON CLI.CD_ENTIDADE = S.CD_ENTIDADE_CLIENTE
LEFT JOIN TB_ENTIDADE TRANS
ON TRANS.CD_ENTIDADE = S.CD_ENTIDADE_TRANSPORTADOR
LEFT JOIN TB_PONTO_GEOREFERENCIADO OG
ON OG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_ORIGEM
LEFT JOIN TB_PONTO_GEOREFERENCIADO DG
ON (S.CD_PONTO_GEO_DESTINO IS NULL AND
DG.CD_PONTO_GEOREFERENCIADO =
FNC_GET_ULTIMA_ENTREGA_PONTO(S.CD_SMP))
OR (S.CD_PONTO_GEO_DESTINO IS NOT NULL AND
DG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_DESTINO)
-- order by using linq?
ORDER BY CLI.NM_APELIDO,
TRANS.NM_APELIDO,
O.DT_OCORRENCIA,
DS_TIPO_OCORRENCIA;
Adding indexes on the columns that are used for joining / filtering would help as well, especially on
TB_SMP.DT_CADASTRO
TB_SMP.cd_tipo_operacao
TB_OCORRENCIA.DT_OCORRENCIA
TB_ENTIDADE.CD_ENTIDADE