Search code examples
mysqlsqldatetimecountinner-join

How to make percentage column in SQL?


Super new to SQL here!

I'm trying to make a third column here with the percentage of redelivered orders vs total orders but I can't figure out how to do it (i.e. for the first row in output the value should be 4%)

Here's my code:

SELECT DISTINCT WH AS Warehouse,
                count(order_id) AS Orders,
                sum(CASE
                        WHEN is_redelivered=1 THEN 1
                        ELSE 0
                    END) AS Redelivered
FROM
  (SELECT DISTINCT o.id AS order_id,
                   wh.code AS WH,
                   o.initial_delivery_date,
                   date(o.delivered_by) AS delivered_by,
                   if(o.delivered_by>o.initial_delivery_date, 1, 0) AS is_redelivered
   FROM `order` o
   JOIN `order_status` os ON o.id = os.id
   JOIN `warehouse` wh ON o.warehouse_id = wh.id
   WHERE o.created_at BETWEEN '2020-11-22' AND '2020-11-28'
     AND os.status != 'Cancelled') orders
GROUP BY WH

Here's the current output


Solution

  • If I follow you correctly, you can do:

    select 
        wh.code as wh, 
        count(*) as cnt_orders,
        sum(o.delivered_by > o.initial_delivery_date) as cnt_redelivered
        100 * avg(o.delivered_by > o.initial_delivery_date) as percent_redelivered
    from `order` o
    join `order_status` os on o.id = os.id
    join `warehouse` wh on o.warehouse_id = wh.id
    where o.created_at between '2020-11-22' and '2020-11-28' and os.status <> 'cancelled'
    group by wh.id, wh.code