'I am trying to build a scatter plot with the average time between now and the last DateTime stamp on X-axis and Location on the Y-axis

I am trying to build a scatter plot with the average time between now and the last DateTime stamp on X-axis and Location on the Y-axis. However, I am struggling to write the correct query for this. I have tried everything but datediff() returns only days, timediff() returns milliseconds (if works) plus I cannot use avg() on the results. My recent attempt is to create timeframes instead of average but can't get my query working. I am a newbie.

SELECT order_reference AS count_of_orders
    ,loc
    ,time_diff
FROM (
    SELECT order_reference
        ,loc
        ,CASE 
            WHEN mindif > 0
                AND mindif < 5
                THEN 'Less than 5min'
            WHEN mindif > 5
                AND mindif < 15
                THEN '5min-15min'
            WHEN mindif > 15
                AND mindif < 30
                THEN '15min-30min'
            WHEN mindif > 30
                AND mindif < 45
                THEN '30min-45min'
            WHEN mindif > 45
                AND mindif < 60
                THEN '45min-1h'
            WHEN mindif > 60
                AND mindif < 75
                THEN '1h-1h15min'
            WHEN mindif > 75
                AND mindif < 90
                THEN '1h15min - 1h30min'
            WHEN mindif > 90
                AND mindif < 105
                THEN '1h30min-1h45min'
            WHEN mindif > 105
                AND mindif < 120
                THEN '1h45min - 2h'
            WHEN mindif > 120
                THEN 'Over 2h'
            END TIME
    FROM (
        SELECT minute(now() - mth.date_time_stamp) AS mindif
            ,soh.order_reference AS order_reference
            ,mth.location AS loc
        FROM sales_order_header soh
        LEFT JOIN sales_order_summary sos
            ON sos.sales_order_header_id = soh.id
        LEFT JOIN sales_order_status sost
            ON sost.id = sos.current_status_id
        LEFT JOIN manufacturing_tracking_history mth
            ON mth.id = sos.current_manufacturing_tracking_history_id
        WHERE sost.STATUS NOT IN (
                "Completed"
                ,"Cancelled"
                )
        ) table1
    ) tab2
WHERE table1.loc IS NOT NULL;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source