Time Cycle issue in SQL Quires. - mysql

In my rails application currently have opening and closing schedules in the application for every restaurant. Like
Monday 5:00 AM to 11:45 PM
Tuesday 6:00 AM to 11:00 PM
Wednesday 9:00 AM to 8:00 PM
Thursday 11:00 AM to 11:45 PM
Friday 5:00 AM to 11:45 PM
Saturday 5:00 AM to 11:45 PM
I have saved the above time into the database with 24hour database time format. It is working perfectly fine. as when i try to get information about the open restaurant time due to 24 hours time i am able to query the data from the database. But now my client wants that the closing time can be 2:00 AM, 2:30 AM as restaurant closes definitely after the mid night.
How it is possible to manage in the SQL Quires? How can i check for a specified period of a time restaurant is open or not?
Currently I have the following Query being executed:
SELECT
COUNT(*)
FROM
`sechedules`
WHERE
`sechedules`.`sechedulable_id` = 16
AND `sechedules`.`sechedulable_type` = 'Operation'
AND (day = 'Wednesday')
AND (opening_time <= '21:28:23'
and closing_time >= '02:28:23'
and is_closed = 0);
I can change the cycle of the day. It can start from the 5:00 AM to 4:59 AM. But how to manage in the database comparisons I'm not getting the best possible solution.

I suggest you formulate your queries around start-time and duration. You could do this from your present dataset. This query gets start time and duration from your table.
select weekday,
start,
stop,
timediff(
if (TIMESTAMPDIFF(MINUTE,start,stop)<0,stop+INTERVAL 24 HOUR, stop),
start) duration
from sechedules
As you can see, it does some monkey business to add 24 hours to the closing time if it shows up as earlier than the opening time.
Then, you can check how many records match a particular time of day like this.
select count(*) cnt
where sechedulable_id = 16
and day = 'Wednesday'
and start <= '21:28:23'
and '21:28:23' <= if(TIMESTAMPDIFF(MINUTE,start,stop)<0,stop+INTERVAL 24 HOUR, stop)

Related

SQL Get Data Between Two dates and Time specifically then break and go to next Date with same Time

Hello guys hope you're having a nice day.
What I'm trying to do is to get data from my db monthly. But what I want is to get data every day for example of all January:
DECLARE
#FromDate Datetime = Convert(datetime,'2022-01-01 12:00:01'),-- all January
#Datetime = Convert(datetime,'2022-01-31 17:00:00')
I have a table called Delivery_order_dtm which has the date and the time of item delivery.
I want every day the data between 12 :00:01 and 17:00:00 ONLY. so when the program finishes fetching data of 1-1-2022 between 12:00:01 and 17:00:00 I want it to go to 02-02-2022 and do the same thing between 12:00:01 and 17:00:00 then go to 03-03-2022 and so on.
Right now how I wrote it it is giving me all the data starting from 01-01-2022 12 PM and ending in 31-01-2022 5 PM that is not what I want.
I want everyday after fetching from 12 pm to 5 pm of this day to break and go to the next day from 12 pm to 5 pm.
Hope you can help me thank you!

How to design table structure for Operating Hours

Problem #1:
How can the table be designed in MySQL in efficient way to structure
1) Store Opening Time,
2) Break Time and
3) Closing Time in a day
For an instance, On Sunday: Opening Time: 7:00AM, Closing Time: 5:00PM, Break Time Start: 1:00PM, Break Time End: 2:30PM.
Problem #2:
How to define the query to search that table for all Stores that are being Opened/Closed between the given range.
For an instance, If user tries to filter the stores for Opening between 9:00AM and 12:00AM. How can I apply query for this filter since it might be possible the Break Time or Closing Time could be within that timeframe.
store_id day open_time break_start break_end close_time
1 mon 7:00AM 1:00PM 2:30PM 5:00PM
1 tue 7:00AM 1:00PM 2:30PM 5:00PM
1 wed 7:00AM 1:00PM 2:30PM 5:00PM
1 thu 7:00AM 1:00PM 2:30PM 5:00PM
1 fri 7:00AM 1:00PM 2:30PM 5:00PM
1 sat Closed
1 sun Closed
Something similar to this. If the user uses criteria: Open Time between: 8:00AM to 2:00PM; to search the store then He must be able to see all the stores that are opened during that timeframe. This timeframe must also include with store open_time. That is, based on criteria provided, the store is Open at 7:00AM, 8:00AM and 9:00AM and until 2:PM.
Better to create three different columns, since you want to query between
Opening time , closing time or break time
create table store_timing
(
store_id int, -- from store table
Opening_Time datetime,
break_time datetime,
closing_time datetime
)
Query :
select *
from store_timing
where Opening_Time<= 'Opening_Time'
and closing_time <= 'closing_time'

how to select monday through sunday in mysql

I have a table that keeps the last few weeks worth of data.
The system goes offline around 3am daily for a few min.
I would like to run a cron job on Monday around 3am to pull last week's data.
How would I select last week's data (Monday 00:00:00 through Sunday 23:59:59)?
I realize one way would be to simply schedule the cron for 00:00:00 on Monday but I want to run this when the system is offline so I need to use MySQL to delimit the data.
Thanks in advance.
The difficulty is going to be your last second on Sunday - you often get into rounding errors there. One way to solve this is just to format or cast from DATETIME to DATE...
SELECT *
FROM logfile
WHERE DATE(logdate) BETWEEN DATE_ADD(CURDATE(), -1 INTERVAL day) AND DATE_ADD(CURDATE(), -8 INTERVAL day)

Is there a way in SQL to determine if certain days are in the same week?

I have the following table 'Schedule' in my database:
**Schedule**
PK Weekday (ie., November 11, 2012)
PK Punch-In (ie., 1:00 PM)
PK Punch-Out (ie., 9:00 PM)
I am tasked with totaling the number of hours worked per week.
For my example Sunday is Day 1 of the week and Saturday is Day 7.
My question is how do I determine which days are in a "week." Is there an SQL command for this? In other words, how do I determine if November 10 is the same week as November 11.
You can use the WEEK() function, which returns week number so WHERE WEEK(date1) = WEEK(date2)
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
Week function should return week number, if this is what you want?

Best way to store weekly event in MySQL?

I have a table of weekly events that run on certain days of the week (e.g. MTWTh, MWF, etc.) and run on a certain time (e.g. 8am-5pm). What's the best way to store day of week information in MySQL to make retrieving and working with the data easiest? My CakePHP app is going to need to retrieve all events happening NOW().
For time of day, I would just use TIME. For days of the week, I had considered a 7-bit bitfield, a varchar ("MTWThFr" type deal) for the days of the week, but both of those seem like clunky solutions (the varchar being clunkier).
Any suggestions?
Here's a straightforward way:
EventID Title Mon Tue Wed Thu Fri Sat Sun BeginningDate EndDate
1 MyEvent 0 0 0 1 0 0 0 14-01-2010 14-01-2033
How to use:
Simply set a 1 on the days you want to run it. Since the 7-days calendar is not likely to change any time soon, that structure should be immutable. You can choose any combination of days.
To recap:
Run every Thursdays:
EventID Title Mon Tue Wed Thu Fri Sat Sun BeginningDate EndDate
1 MyEvent 0 0 0 1 0 0 0 14-01-2010 14-01-2033
Run every Thursdays & Mondays:
EventID Title Mon Tue Wed Thu Fri Sat Sun BeginningDate EndDate
1 MyEvent 1 0 0 1 0 0 0 14-01-2010 14-01-2033
Further more, you get only one row per event schedule, which is easier and cleaner to handle programmatically.
For example, to find all events to be executed on monday, do:
select * from Events where Mon = 1
Can you add an DayOfWeek column in your table and make it an int? Valid values for that would be 1 thru 7. You could add a constraint on that to enforce that rule. For time, how about a BeginTime columns and an EndTime column? They would be int's as well 0-24
For an event at 5:00 pm on Monday would look like this in your table
Event_ID DayOfWeek BeginTime EndTime
1 2 1700 1800
Why not have several lines, each line having only one column containing the day of week. This column would be just a simple :
ENUM("Monday", "Tuesday", ...)
Then, in PHP you could use date and strtotime functions to get the name of the day :
echo date('l');
echo date('l', strtotime('mon'));
// Outputs "Monday"
It is way more readable to store the name of the day.
In case anyone coming this way again I am using SMTWHFA quite efectively with a simple string search.
So Monday Wednesday Friday would be MWF and Sunday Monday Thursday would be SMH. Takes a while to get used to H=Thursday (second letter) and Saturday=A but it works!
Since there won't be any new days of the week invented (I hope!) you could just create a bool column for each day. Then, if you are running a query to find events on a Friday, it would simply be (with a bit of pseudocode):
SELECT eventName
FROM events
WHERE fridayBool = true
AND eventStartTime < NOW()
AND eventEndTime > NOW();
In that example the name of the column you would store in an array in your code, and check today's date to see what day of the week it is, which then selects the proper name out of the array before creating the query.
Not the most elegant, but it should work.
Edit...
Example table columns:
eventID
eventName
eventStartTime
eventEndTime
sundayBool
mondayBool
...
saturdayBool
Break the weekly information into a separate table entirely:
events: id, beginTime, endTime, name, description
eventsbyday: id, dayofweek, event_id
This will allow you to query eventsbyday according to the current day of the week:
SELECT events.name, events.beginTime, events.endTime FROM eventsbyday JOIN events ON eventsbyday.event_id=events.id WHERE dayofweek=0
This is very rough code, but the idea is to break out the weekly information, allowing you to have the same event associated with multiple days of the week.