In a lengthy insert SQL statement, need to select whatever ship_to_cust_id is in first row...ONLY IF...there is no PRIORITY 1 row. These are simplified versions of the SQL. How do I combine, so it looks for priority 1 first, and only then selects the first row's ship_to_cust_id if no priority 1 row is found? These are abbreviated SQL that work to pull both; how to merge into one statement?
SELECT
s.cust_id, s.ship_to_cust_id, s.sldto_priority_nbr
FROM
sysadm.ps_cust_shipto s, sysadm.PS_CUST_BILLTO b
WHERE
b.setid = 'SHARE'
AND b.cust_id = '90677671'
AND b.setid = s.setid
AND b.cust_id = s.cust_id
AND s.ship_to_cust_id IN (SELECT x.ship_to_cust_id
FROM sysadm.ps_cust_shipto x
WHERE x.sldto_priority_nbr = 1
AND x.cust_id = b.cust_id)
SELECT
s.cust_id, s.ship_to_cust_id, s.sldto_priority_nbr
FROM
sysadm.ps_cust_shipto s, sysadm.PS_CUST_BILLTO b
WHERE
b.setid = 'SHARE'
AND b.cust_id = '90677671'
AND b.setid = s.setid
AND b.cust_id = s.cust_id
AND s.ship_to_cust_id IN (SELECT y.ship_to_cust_id
FROM sysadm.ps_cust_shipto y
WHERE rownum = 1
AND y.cust_id = b.cust_id)
Here is sample input data on the table we need to extract from for this particular value. This one has Priority 1, but sometimes it is missing.
SETID CUST_ID SHIP_TO_CUST_ID SLDTO_PRIORITY_NBR LAST_OPRID
SHARE 90677671 114369323 2 JENNIFERBRYAN
SHARE 90677671 114479768 3 JENNIFERBRYAN
SHARE 90677671 90677695 1 TARAARROYO
I have tried using CASE logic, since if the condition is satisfied re the priority, it would not evaluate further. CASE works that way to terminate once a condition is satisfied.
But I have tried many versions and nothing works. I read somewhere that when CASE is used in a select, it can only do equal/not-equal evaluations; not conditional logic, so that might be the problem.
This code will be in a PeopleSoft App Engine. It is part of a long insert statement's conditional logic, so not as simple as the logic presented. However, above addresses the main components...but I need to combine the logic re priority and rownum. If a priority 1 row is found, use that ship_to_cust_id; we don't need to worry about rownum in that case. But if no priority 1, then we can use the ship_to_cust_id from the first row.