Complex Query Optimization - sql

Running Postres 7.4 (yep upgrading)
This is a view query and it's used a lot but takes longer than I would like. Any Optimization Suggestions? Any field with a Id in the name is indexed
SELECT
db_tbl_1.field_id, s."Field ID" AS foreign_field_id,
s."Field Name" AS field_name,
CASE
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 3) = '01' THEN 'Field Label 1'
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 4) = '321' THEN 'Field Label 1'
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 5) = '1234' THEN 'Field Label 1'
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 6) = '55555' THEN 'Field Label 1'
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 3) = '76' THEN 'Field Label 2'
END AS new_field, s.field_1,
db_tbl_2.field_2, db_tbl_1.field_2_a,
db_tbl_1.field_3, db_tbl_1.field_4,
db_tbl_1.field_5, db_tbl_1.field_6, db_tbl_1.field_date_1,
db_tbl_1.field_7, db_tbl_2.field_8 AS new_field_name,
s."Field Date" AS field_date, db_tbl_1.created_date,
CASE
WHEN (((DATE_TRUNC('month', "Field Date") + INTERVAL '2 MONTH') - "Field Date" > 60) AND
((DATE_TRUNC('month', "Field Date") + INTERVAL '2 MONTH') - "Field Date" <= 92))
THEN (DATE_TRUNC('month', "Field Date") + INTERVAL '2 MONTH')
-- the most days in a three month span can be 92
ELSE (DATE_TRUNC('month', "Field Date") + INTERVAL '3 MONTH')
END AS next_date
FROM db_schema_1.db_tbl_1, db_schema_1.db_tbl_2, "Table S" AS s
WHERE db_tbl_1.program_level_id = db_tbl_2.id
AND db_tbl_1.field_id = s."Another ID"
AND (CASE
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 3) = '01' THEN 1
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 4) = '321' THEN 1
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 5) = '1234' THEN 1
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 6) = '55555' THEN 1
WHEN SUBSTRING(s."Field ID" FROM 0 FOR 3) = '76' THEN 1
ELSE 0
END) = 1

Try to change the last statement, where you are using the case statement because the query will evaluate all of them. and then check if is equals to 1, you should try and "OR" statement, because if one is correct, it will not evaluate the other alternatives. It should help you a bit. Something like this.
AND ( SUBSTRING(s."Field ID" FROM 0 FOR 3) = '01' OR
SUBSTRING(s."Field ID" FROM 0 FOR 4) = '321' OR
SUBSTRING(s."Field ID" FROM 0 FOR 5) = '1234' OR
SUBSTRING(s."Field ID" FROM 0 FOR 6) = '55555' OR
SUBSTRING(s."Field ID" FROM 0 FOR 3) = '76'
)

Related

ORA-01476: Divisor is equal to zero

I have this query that I've been given to fix and I cannot understand why its causing error. I reviewed similar topics involving the max function and the null function but I can't seem to make them work without throwing another error.
select case when count(trlr_num) > 0 then 'Inbounds Need Closed'
else 'All Good'
end as "Inbounds To Be Closed"
from (select t.trlr_num,
r.invnum "Invoice",
to_char(nvl(max(rl.init_rcv_dte), sysdate), 'MM/DD/YY HH:MI AM') as "Begin receive date",
round(sum(rl.idnqty) / sum(rl.expqty) *100, 1) as "% Received%"
from trlr t
join rcvinv r
on t.trlr_num = r.trknum
join rcvlin rl
on r.trknum = rl.trknum
and r.supnum = rl.supnum
and r.invnum = rl.invnum
and r.wh_id = rl.wh_id
join rcvtrk rt
on r.trknum = rt.trknum
and t.trlr_id = rt.trlr_id
and r.wh_id = rt.wh_id
where t.yard_loc_wh_id = 'US_3218'
and rt.rcvtrk_stat <> 'C'
and r.invtyp not in ('PKG', 'XFR')
and (rl.rcvsts <> 'QI' or (rl.rcvsts = 'QI' and t.trlr_seal1 is not null and t.trlr_seal2 is not null))
group by t.trlr_num,
r.invnum
having sum(rl.idnqty) / sum(rl.expqty) = 1
and nvl(max(rl.init_rcv_dte), sysdate) < sysdate -2)

Teradata SQL Update Table "Query Error 3802 Database 'oo' does not exist"

I need help with the following query code. Currently it is giving me the 3802 query error "Database does not exist". Well I did my "from" selection query as 'oo', so that definitely exists. This worked yesterday with some minor changes to the "from" part of the query. The assistance is appreciated.
UPDATE snd_bqa.open_order_all_test
FROM (
SELECT
CASE WHEN m.order_status_desc = 'Completed' AND NVL(c.supptype, 'NULL') <> 'CAN'
THEN 'YES'
ELSE 'NO'
END AS "Order Complete",
CASE WHEN m.order_status_desc = 'Completed' AND c.supptype = 'CAN'
THEN 'YES'
ELSE 'NO'
END AS "Order Cancelled",
CASE WHEN pih.effective_start_date IS NOT NULL AND pih.product_instance_status_code = 3
THEN 'YES'
ELSE 'NO'
END AS "Service Active in PB",
c.ordernumber,
c1.order_requested_due_date,
c.creationdate AS "Order Creation Date",
c.ordersubmitdate AS "Order Submit Date",
c.lastupdateddate,
c.supptype,
m.order_status_desc,
m.phase_stage,
cus.sub_nasp_id,
cus.gch_id,
b.work_order_no,
b.itemcode,
b.instance_id,
COALESCE(b.specific_date, b.standard_date) AS "Service Req Due Date",
m.milestone,
m.milestone_desc,
cus.custlegalname,
a.account_number,
vle.vle_id,
vle.currency_cd,
cus.duns_number,
a.cle_vle_id,
CURRENT_TIMESTAMP(2) AS "Originally Loaded",
CURRENT_TIMESTAMP(2) AS "Last Upd",
CAST((CASE WHEN m.order_status_desc = 'Completed' AND NVL(c.supptype, 'NULL') <> 'CAN'
THEN c.lastupdateddate
ELSE NULL
END) AS TIMESTAMP(2)) "Order Completed Date",
CAST((CASE WHEN m.order_status_desc = 'Completed' AND c.supptype = 'CAN'
THEN c.lastupdateddate
ELSE NULL
end) AS TIMESTAMP(2)) "Order Cancelled Date",
pih.last_modified AS "Service Last Modified Date",
pih.effective_start_date AS "Service Effective Date"
FROM (
SELECT *
FROM edw_stg_ord_cw_vw.cwpc_basketitem
WHERE itemcode LIKE 'PR%'
AND (instance_id, lastupdateddate) IN (
SELECT instance_id, MAX(lastupdateddate)
FROM edw_stg_ord_cw_vw.cwpc_basketitem
GROUP BY instance_id
)) AS b
INNER JOIN edw_stg_ord_cw_vw.cworderinstance AS c
ON c.basket_id = b.basketid
AND c.isactive = 1
AND c.request_type = 'ORD'
LEFT JOIN (
SELECT c.ordernumber,
MAX(COALESCE(b.specific_date, b.standard_date)) order_requested_due_date
FROM edw_stg_ord_cw_vw.cworderinstance AS c
INNER JOIN edw_stg_ord_cw_vw.cwpc_basketitem AS b
ON b.basketid = c.basket_id
AND c.request_type = 'ORD'
AND c.isactive = 1
GROUP BY c.ordernumber
) AS c1
ON c1.ordernumber = c.ordernumber
LEFT JOIN edw_stg_ord_cw_vw.uno_customer AS cus
ON cus.cworderid = c.cwdocid
AND cus.oi_customer_id = c.ordering_customer_id
LEFT JOIN edw_stg_ord_cw_vw.uno_milestone AS m
ON m.milestone_id = c.milestone_id
LEFT JOIN edw_stg_ord_cw_vw.uno_account AS a
ON a.cworderid = c.cwdocid
AND b.account_id = a.oi_account_id
LEFT JOIN edw_stg_ord_cw_vw.uno_cle_vle AS vle
ON vle.cle_vle_id = a.cle_vle_id
AND c.cwdocid = vle.cworderid
INNER JOIN snd_bqa.open_order_all_test tst
ON tst."Service Instance ID" = b.instance_id
AND tst."Milestone" <> m.milestone
LEFT JOIN edw_pb_stg_vw.product_instance_history AS pih
ON pih.general_5 = tst."Service Instance ID"
WHERE cus.sub_nasp_id NOT IN ('19HNYO', '23MAXA', '19HNYR', '10INTD')
AND COALESCE(b.specific_date, b.standard_date, c1.order_requested_due_date) BETWEEN CURRENT_DATE - 60 AND CURRENT_DATE - 30
) oo
SET "Order Complete" = oo."Order Complete",
"Order Cancelled" = oo."Order Cancelled",
"Service Active in PB" = oo."Service Active in PB",
"Service Order Number" = oo.ordernumber,
"Order Requested Due Date" = oo.order_requested_due_date,
"Order Last Updated" = oo.lastupdateddate,
"Order Creation Date" = oo."Order Creation Date",
"Order Submit Date" = oo."Order Submit Date",
"Order Supp Type" = oo.c.supptype,
"Order Status" = oo.order_status_desc,
"Phase Stage" = oo.phase_stage,
"Milestone" = oo.milestone,
"Milestone Description" = oo.milestone_desc,
"NASP ID" = oo.sub_nasp_id,
"GCH ID" = oo.gch_id,
"Work Order Numbers" = oo.work_order_no,
"Product Code" = oo.itemcode,
"Service Requested Due Date" = oo."Service Req Due Date",
"Customer Name" = oo.custlegalname,
"Account Number" = oo.account_number,
"VLE ID" = oo.vle_id,
"Currency Code" = oo.currency_cd,
"DUNs Number" = oo.duns_number,
"CLE VLE ID" = oo.cle_vle_id,
"Last Record Update" = oo."Last Upd",
"Order Completed Date" = oo."Order Completed Date",
"Order Cancelled Date" = oo."Order Cancelled Date",
"Service Last Modified Date" = oo."Service Last Modified Date",
"Service Effective Date" = oo."Service Effective Date"
WHERE open_order_all_test."Service Instance ID" = oo.instance_id
;
I found the issue. I had oo.c.supptype, when it should have just been oo.supptype
This caused Teradata to think 'oo' was referring to a database. case closed.

Issue with CASE statement in a calculated column

I have a SELECT statement which works fine up until the CASE part, I think it's just a case of syntax error and the lead time bit. I am using Oracle APEX.
I get the error;
ORA-00923: FROM keyword not found where expected
select
supplier.companyname as "Supplier",
purchaseorder.orderdate as "Order Date",
purchaseorder.duedate as "Due Date",
popayment.datedelivered as "Delivered",
(popayment.paymentdate - popayment.datedelivered) - 31 as paidontime,
/* this is the same as the next one (this works fine) */
(popayment.datedelivered - purchaseorder.duedate) - 1 as deleiverylate,
/* trying to advance the previous query (this does not work) */
popayment.datedelivered - purchaseorder.duedate -1,
case when "lead time" <0 then 'early'
when "lead time" >0 then 'late'
else 'on time'
end as "lead time";
from supplier, purchaseorder, suppliercontact, popayment
where
purchaseorder.SUPPLIERCONTACTID2 = suppliercontact.suppliercontactid
and
supplier.supplierid = suppliercontact.supplierid
and
purchaseorder.purchaseorderid = popayment.purchaseorderid
order by COMPANYNAME
Thanks for any help
Dangerous Brian
Is this what you want?
SELECT supplier.companyname AS "Supplier",
purchaseorder.orderdate AS "Order Date",
purchaseorder.duedate AS "Due Date",
popayment.datedelivered AS "Delivered",
(popayment.paymentdate - popayment.datedelivered) - 31 AS paidontime,
/* this is the same as the next one (this works fine) */
(popayment.datedelivered - purchaseorder.duedate) - 1 AS deleiverylate,
/* trying to advance the previous query (this does not work) */
CASE
WHEN popayment.datedelivered - purchaseorder.duedate -1 <0
THEN 'early'
WHEN popayment.datedelivered - purchaseorder.duedate -1 >0
THEN 'late'
ELSE 'on time'
END AS "lead time"
FROM supplier,
purchaseorder,
suppliercontact,
popayment
WHERE purchaseorder.SUPPLIERCONTACTID2 = suppliercontact.suppliercontactid
AND supplier.supplierid = suppliercontact.supplierid
AND purchaseorder.purchaseorderid = popayment.purchaseorderid
ORDER BY COMPANYNAME
You should delete ; at end as "lead time";

Prepend Integer Result with string text of "1:" to create ratio

The following query returns a single number, representing the n in a 1:N ratio. Instead of just returning a single number, how can I prepend the integer value with the following text 1: to give the result the correct ratio format?
select round((sum (case when unified_rollup_level_1 = "Company A" and person_type = "Employee" and worker_status = "Active" then 1 else 0 end)) /
(sum (case when unified_rollup_level_1 = "Company A" and person_type = "Employee" and worker_status = "Active" and job_level IN ("08", "09") then 1 else 0 end)),0)
Assuming it would be for MySQL:
select
CONCAT("1:", round((sum (case when unified_rollup_level_1 = "Company A"
and person_type = "Employee"
and worker_status = "Active"
then 1
else 0
end)) /
(sum (case when unified_rollup_level_1 = "Company A"
and person_type = "Employee"
and worker_status = "Active"
and job_level IN ("08", "09")
then 1
else 0
end)),0))
I hope it helps.
You can prepend text by just doing this:
SELECT "Foo" + stuff FROM table;
In this case, if stuff was 3, the result would be "Foo3" (without the quotes).
So in your case:
SELECT "1:" + ... -- the rest of it goes here

DB2 SQL Select Statement & Group By

I am having trouble getting my query to group correctly. I need to include the TELLERACTIVITY.ENTRY_DATE date column so I can filter by the date later on. However, I do not want it to group by the TELLERACTIVITY.ENTRY_DATE date because it gives me more results than I want.
SELECT DISTINCT ACTIVITYINFO.MEMBER_NBR AS "Member Number"
,ACCOUNT.ACCOUNT_NBR AS "Account Number"
,TELLERACTIVITY.FOCUS_TELLER_ID AS "Teller ID"
,TELLERACTIVITY.ENTRY_DATE AS "Date"
,SUM(( CASE WHEN OPERATOR.BRANCH_NBR = 1 THEN 1
ELSE 0
END )) AS "Branch 1"
,SUM(( CASE WHEN OPERATOR.BRANCH_NBR = 2 THEN 1
ELSE 0
END )) AS "Branch 2"
,SUM(( CASE WHEN OPERATOR.BRANCH_NBR = 3 THEN 1
ELSE 0
END )) AS "Branch 3"
,SUM(( CASE WHEN OPERATOR.BRANCH_NBR = 4 THEN 1
ELSE 0
END )) AS "Branch 4"
FROM TELLERACTIVITY
JOIN OPERATOR
ON TELLERACTIVITY.FOCUS_TELLER_ID = OPERATOR.OPR_NBR
JOIN ACTIVITY
ON TELLERACTIVITY.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
AND TELLERACTIVITY.FOCUS_TELLER_ID = ACTIVITY.FOCUS_TELLER_ID
AND TELLERACTIVITY.ENTRY_DATE = ACTIVITY.ENTRY_DATE
JOIN ACTIVITYINFO
ON ACTIVITY.ACTIVITY_ID = ACTIVITYINFO.ACTIVITY_ID
JOIN ACCOUNT
ON ACTIVITYINFO.MEMBER_NBR = ACCOUNT.MEMBER_NBR
AND ACTIVITYINFO.ACCOUNT_NBR = ACCOUNT.ACCOUNT_NBR
WHERE TELLERACTIVITY.FOCUS_TELLER_ID < 6000
GROUP BY ACTIVITYINFO.MEMBER_NBR
,ACCOUNT.ACCOUNT_NBR
,OPERATOR.BRANCH_NBR
,TELLERACTIVITY.FOCUS_TELLER_ID
,TELLERACTIVITY.ENTRY_DATE
ORDER BY ACTIVITYINFO.MEMBER_NBR