-- In sql_store database, create function get_percent_shipped_orders_for_customer().
-- No exercises for creating functions are given in the course, so I thought
-- of this challenge in order to practice.
-- Don't forget to include the appropriate attributes,
-- such as DETERMINISTIC, READS SQL DATA, MODIFIES SQL DATA.
USE sql_store;
DROP FUNCTION IF EXISTS get_percent_shipped_orders_for_customer;
DELIMITER $$
CREATE FUNCTION get_percent_shipped_orders_for_customer
(
customer_id INT
)
RETURNS DECIMAL(9,2)
READS SQL DATA
BEGIN
DECLARE count_of_all_orders INT;
DECLARE count_of_shipped_orders INT;
DECLARE percent_shipped_orders DECIMAL(9,2);
SELECT COUNT(*)
INTO count_of_all_orders
FROM orders o
WHERE
o.customer_id = customer_id;
SELECT COUNT(*)
INTO count_of_shipped_orders
FROM orders o
WHERE
o.customer_id = customer_id AND
shipped_date IS NOT NULL;
IF count_of_all_orders = 0 THEN
RETURN 0;
ELSE
RETURN ROUND(count_of_shipped_orders/count_of_all_orders, 2);
END IF;
END$$
DELIMITER ;
I then used this custom function to create a Percent Shipped Orders for all customers:
USE sql_store;
SELECT
CONCAT_WS(" ", c.first_name, c.last_name) AS customer,
get_percent_shipped_orders_for_customer(c.customer_id) AS pct_shipped_orders
FROM
customers c
ORDER BY pct_shipped_orders DESC, customer;
I obtain the following report: