Query that returns the difference in hours between two dates considering working days - MYSQL

Asked

Viewed 17 times

0

I have a demand where I need to generate a query that returns the amount of existing records in a table, given the difference, in hours, between two dates.

The difference between the dates I can pick up as follows:

TIMESTAMPDIFF(HOUR, date1, date2)

It happens that I need to consider working days (Mon to Fri), from 08:00 to 18:00 and Saturday, from 08:00 to 12:00

I know I can take the day of the week with the job DAYOFWEEK.

I have the query that returns the amount of records grouped by the interval of hours:

SELECT CASE
         WHEN info = 1 THEN '0-4'
         WHEN info = 2 THEN '4-8'
         WHEN info = 3 THEN '8-16'
         WHEN info = 4 THEN '16-24'
         WHEN info = 5 THEN '24-32'
         WHEN info = 6 THEN '> 32'
       END as info, sum(value) as value
FROM (
   (SELECT 
        CASE
            WHEN TIMESTAMPDIFF(HOUR, (  SELECT launch_date 
                                        FROM shipping 
                                        WHERE id = s.id AND DAYOFWEEK(launch_date) BETWEEN 2 AND 6
                                     ), 
                                      so.collection_expected_date) < 4 THEN 1
            WHEN TIMESTAMPDIFF(HOUR, s.launch_date, so.collection_expected_date) BETWEEN 4 AND 8 THEN 2
            WHEN TIMESTAMPDIFF(HOUR, s.launch_date, so.collection_expected_date) BETWEEN 8 AND 16 THEN 3
            WHEN TIMESTAMPDIFF(HOUR, s.launch_date, so.collection_expected_date) BETWEEN 16 AND 24 THEN 4
            WHEN TIMESTAMPDIFF(HOUR, s.launch_date, so.collection_expected_date) BETWEEN 24 AND 32 THEN 5
            WHEN TIMESTAMPDIFF(HOUR, s.launch_date, so.collection_expected_date) > 32 THEN 6
        END as info,
        count(*) as value 
    FROM shipping s
    INNER JOIN shipping_origin so ON (so.id = (SELECT id FROM shipping_origin WHERE shipping_id = s.id ORDER BY collection_expected_date LIMIT 1))
    WHERE s.shipper_id = :shipperId AND s.launch_date BETWEEN :startDate and :endDate 
        AND s.status not in ('CANCELED', 'EXPIRED', 'EXCLUDED') AND (:operationGroupId IS NULL OR s.shipper_operation_group_id = :operationGroupId) 
        AND s.freight_type = 'CIF'
    GROUP BY info
    ORDER BY info) UNION
    (SELECT 1 as info, 0 as value FROM dual) UNION
    (SELECT 2 as info, 0 as value FROM dual) UNION
    (SELECT 3 as info, 0 as value FROM dual) UNION
    (SELECT 4 as info, 0 as value FROM dual) UNION
    (SELECT 5 as info, 0 as value FROM dual) UNION
    (SELECT 6 as info, 0 as value FROM dual)
) a
GROUP BY info

I’m having difficulty adjusting this query, considering the working days and the respective times cited in the description.

Can someone help me?

Thank you.

  • There would be no need to consider the holidays either?

  • For this scenario, there is no need

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.