Search code examples
mysqlsqltimeanalysis

sql - select case statement to add time cut-off


I have this table that contains created order time, as well as received, inprocess, assigned, and delivered time. As well as a view that calculates their average times. I'm trying to add a clause that has orders submitted after 8:00PM (closing time) be taken in as 8:00AM(business opens)the next day to maintain the correct average times. Here is the orders [![table: ][1]][1] And this is the view I'm using to calculate the average time

SELECT 
        AVG(TIMESTAMPDIFF(MINUTE,
            `sales`.`received_time`,
            `sales`.`inprocess_time`)) AS `avg_prepare`,
        AVG(TIMESTAMPDIFF(MINUTE,
            `sales`.`inprocess_time`,
            `sales`.`assigned_time`)) AS `avg_assign`,
        AVG(TIMESTAMPDIFF(MINUTE,
            `sales`.`assigned_time`,
            `sales`.`delivered_time`)) AS `avg_delivery`,
        AVG(TIMESTAMPDIFF(MINUTE,
            `sales`.`received_time`,
            `sales`.`delivered_time`)) AS `avg_total`
    FROM
        `customer_orders` `sales`

Thank you for your help!


Solution

  • SELECT 
            AVG(TIMESTAMPDIFF(MINUTE,
                `sales`.`received_time`,
                `sales`.`inprocess_time`)) AS `avg_prepare`,
            AVG(TIMESTAMPDIFF(MINUTE,
                `sales`.`inprocess_time`,
                `sales`.`assigned_time`)) AS `avg_assign`,
            AVG(TIMESTAMPDIFF(MINUTE,
                `sales`.`assigned_time`,
                `sales`.`delivered_time`)) AS `avg_delivery`,
            AVG(TIMESTAMPDIFF(MINUTE,
                `sales`.`received_time`,
                `sales`.`delivered_time`)) AS `avg_total`
        FROM
            (SELECT 
                  CASE WHEN TIME(received_time) > '20:00:00' THEN DATE_ADD(DATE(received_time), INTERVAL 32 HOUR) 
                       WHEN TIME(received_time) <= '07:59:59' THEN DATE_ADD(DATE(received_time), INTERVAL 8 HOUR) 
                       ELSE received_time 
                  END as received_time
               ,inprocess_time
               ,assigned_time
               ,delivered_time
            FROM `customer_orders`
            WHERE created_on between '2020-08-01' AND '2020-09-01'
            ) AS `sales`