mysqldatabaseifnull

Using IFNULL function mysql to set null to zero


I have tables on my database with the following schema:

customers (customerID: integer, fName: string, lName: string)
items (itemID: integer, description: string, price: integer)
orders (orderID: integer, itemID: integer, aID: integer, customerID:integer, date: date)

and the following code:

SELECT c.customerID, COUNT(DISTINCT o.orderID) AS number_of_orders, 
       ROUND(SUM(i.price) / COUNT(DISTINCT o.orderID),2) AS average 
  FROM customers c 
     LEFT JOIN orders o 
            ON o.customerID = c.customerID 
           AND o.date >= '2013-03-01' 
           AND o.date < '2013-04-01' 
     LEFT JOIN items i 
            ON o.itemID = i.itemID 
GROUP BY c.customerID

which returns three values: customer ID, number of orders per customer, and average spending per customer. With the code as it is now, the average spending per customer is returned as blank (null). I am having trouble using the IFNULL function to set the average spending per customer to 0.00 if the customer did not order anything in march 2013 (i.e., if number of orders per customer in march is zero). Any help will be very much appreciated!


Solution

  • Without seeing your IFNULL attempts, this logic works for me:

    SELECT c.customerID, 
    COUNT(DISTINCT o.orderID) AS number_of_orders, 
    ROUND(IFNULL( (SUM(i.price) / COUNT(DISTINCT o.orderID)), 0.00),2) AS average,
    FORMAT(IFNULL(ROUND( (SUM(i.price) / COUNT(DISTINCT o.orderID)),2), 0), 2) AS averageWithFormat 
    FROM customers c 
    LEFT JOIN orders o ON o.customerID = c.customerID AND o.date >= '2013-03-01' AND o.date < '2013-04-01' 
    LEFT JOIN items i ON o.itemID = i.itemID 
    GROUP BY c.customerID
    

    Returns: 0.00

    I have two entries for average in my statement because in my local MySQL Workbench, the first one returns with two decimal precision but doesn't in SQLFiddle. I added the second entry with the FORMAT syntax to force the two decimal precision, if needed.