Skip to content
Advertisement

Categorize datetime value to shifts where shift ends on the next day

I have a MySQL query for example:

My table only have qty and filedatetime columns.

Based on this query is it possible to query out the following conditions:

  • if filedatetime is filedatetime >= ‘2019-08-01 06:30:00’ and filedatetime < ‘2019-08-01 18:30:00’ then
    • assign value ‘Day’ to column shift
    • assign value ‘2019-08-01’ to column shiftDate
  • if filedatetime >= ‘2019-08-01 18:30:00’ and filedatetime < ‘2019-08-02 06:30:00’ then
    • assign value ‘Night’ to column shift
    • assign value ‘2019-08-01’ to column shiftDate

So this how the result will be look like:

Advertisement

Answer

You can use Time() function to extract time (hh:mm:ss) portion out of a datetime value. Once we have determined that, we can use CASE .. WHEN conditional expression, to check whether “Day” or “Night” shift based on your defined conditions. Also, we can use Date() function to extract the date (YYYY-mm-dd) portion and add/subtract 1 day accordingly.

We can then GROUP BY on these calculated expressions, and calculate sum of the qty; no need of using a subquery for further aggregation:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement