简体   繁体   中英

Oracle SQL if statement?

how would it be possible to check if a certain value in salesman_id is null, and if it is, assign it to something else (in this case, 0)?

here's what i've wrote up so far:

SELECT O.SALESMAN_ID, SUM(OI.UNIT_PRICE * QUANTITY)
FROM ORDERS O, ORDER_ITEMS OI
GROUP BY O.SALESMAN_ID
ORDER BY O.SALESMAN_ID;
SELECT nvl(O.SALESMAN_ID,0), SUM(OI.UNIT_PRICE * QUANTITY)
FROM ORDERS O, ORDER_ITEMS OI
GROUP BY nvl(O.SALESMAN_ID,0)
ORDER BY 1;

I would suggest:

SELECT COALESCE(O.SALESMAN_ID, 0) as SALESMAN_ID, SUM(OI.UNIT_PRICE * QUANTITY)
FROM ORDERS O JOIN
     ORDER_ITEMS OI
     ON o.ORDER_ID = OI.ORDER_ID. -- guessing at the relationship
GROUP BY COALESCE(O.SALESMAN_ID, 0)
ORDER BY COALESCE(O.SALESMAN_ID, 0);

Your query as written would produce non-sensical results. Always use proper, explicit, standard , readable JOIN syntax. Never use commas in the FROM clause.

For completeness sake, a further option would be...

SELECT salesman_id, SUM(total)
FROM (
    SELECT CASE WHEN o.salesman_id IS NULL 
           THEN 0 
           ELSE o.salesman_id as SALESMAN_ID, 
     OI.UNIT_PRICE * QUANTITY AS total 
    FROM ORDERS O JOIN
     ORDER_ITEMS OI
     ON o.ORDER_ID = OI.ORDER_ID
  ) AS ilv
GROUP BY salesman_id;

But null is a value too....

SELECT CASE WHEN ilv.salesman_id IS NULL 
           THEN 0 
           ELSE ilv.salesman_id as SALESMAN_ID,
    total
FROM (
    SELECT salesman_id 
     SUM(OI.UNIT_PRICE * QUANTITY) AS total 
    FROM ORDERS O JOIN
     ORDER_ITEMS OI
     ON o.ORDER_ID = OI.ORDER_ID
    GROUP BY sles,an_id
  ) AS ilv;

I think the query is incorrect, you need to join orders and ORDER_ITEMS using order_id

scott

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM