How can I calculate the number of minutes per day between a daterange - ssms

First off I apologize I do not even know where to start and haven't been able to find anything specific to this particular question.
I have a table with datetimes (start and end) and i need to find a way to get minutes/hours between those days. It could either be a sum of the time on weekdays or a some kind of pivot on each day and grouping by the ID number. I had thought to assign a value to the number of days however the times are random and do not start/end at midnight so I am at a loss as how to approach this.
Here are some examples of the date/time format if that helps.
startdate 2018-12-14 10:53:01
enddate 2018-12-27 11:50:00
Any helps or hints would be greatly appreciated!
Edit
forgot to include I am working in SQL Server (SSMS)
Editing For Additional Clarification
Here is a sample date range with an ID number, I wanted to keep it simple.
|ID number| start time |end time
|1 |12/14/2018 10:53|12/17/2018 12:00
here is what I'm trying to achieve (the separation of each date range/ID #)
ID number| start time |end time |mins|
1 | 12/14/2018 10:53|12/14/2018 23:59|786 |
1 | 12/15/2018 0:00 |12/15/2018 23:59|1439|
1 | 12/16/2018 0:00 |12/16/2018 23:59|1439|
1 | 12/17/2018 0:00 |12/17/2018 12:00|960 |

The MINUTE parameter of the DATEDIFF function can be used to determine the difference in minutes between two datetime columns. As below, the second parameter is the start date and the third parameter is the end date, with the result being the amount of time in the specified interval (days, minutes, etc.) from the start to the end date. If you need to find the number of hours between these two columns the HOUR parameter can be used for this. Grouping can be performed as well, as in the second example.
DATEDIFF:
SELECT DATEDIFF(MINUTE, StartDateColumn, EndDateColumn)
DATEDIFF with Grouping and Aggregation:
SELECT ColumnA, SUM(DATEDIFF(MINUTE, StartDateColumn, EndDateColumn)) as DifferenceInMinutes
FROM YourSchema.YourTable
GROUP BY ColumnA

Related

Count overnight hours as one day

I have a dataset where certain operations occur during the overnight hours which I'd like to attribute to the day before.
For example, anything happening between 2/23 8pm and 2/24 6am should be included in 2/23's metrics rather than 2/24. Anything from 6:01 am to 7:59pm should be counted in 2/24's metrics.
I've seen a few posts about decrementing time by 6 hours but that doesn't work in this case.
Is there a way to use an If function to specify that midnight-6am should be counted as date-1 rather than date without affecting the metrics for the 6am - 7:59pm hours?
Thanks in advance! Also, a SQL newbie here so apologies if I have lots of followup questions.
You can use date_add with -6 hours and then optionally cast the timestamp as a date.
create table t (dcol datetime);
insert into t values
('2022-02-25 06:01:00'),
('2022-02-25 06:00:00'),
('2022-02-25 05:59:00');
SELECT CAST(DATE_ADD(dcol, INTERVAL -6 HOUR)AS DATE) FROM t;
| CAST(DATE_ADD(dcol, INTERVAL -6 HOUR)AS DATE) |
| :-------------------------------------------- |
| 2022-02-25 |
| 2022-02-25 |
| 2022-02-24 |
db<>fiddle here
As said in the comments, your requirement is the occurrences in a 6 AM to 6 AM day instead of a 12-12 day. You can achieve this by decreasing the time by 6 hours as shown in #Kendle’s answer. Another way to do it is to use an IF condition as shown below. Here, the date is decremented if the time is before 6 AM on each day and the new date is put in a new column.
Query:
SELECT
IF
(TIME(eventTime) <= "06:00:00",
DATE_ADD(DATE(eventTime), INTERVAL -1 DAY),
DATE(eventTime)) AS newEventTime
FROM
`project.dataset.table`
ORDER BY
eventTime;
Output from sample data:
As seen in the output, timestamps before 6 AM are considered for the previous day while the ones after are considered in the current day.

Determine date gaps

I have a SQL Server table that has a begin date and end date column that denote the beginning and ending range of a pricing schedule.
As the years go by, many versions of this same schedule will be created, with different beginning and ending dates.
What I would like to do is ensure that the user doesn't add, or, in some cases edit, a beginning or ending date in such a way that days would be excluded in the overall time frame.
So if the data looked like this:
Start | End
-----------+--------------
01/01/2015 | 06/30/2015
07/01/2015 | 09/30/2016
10/01/2016 | 12/31/2020
So, lets assume I attempted to revised the last row Start to 10/15/2016. That would create a gap of days between 10/01/2016 and 10/14/2016, but I have no idea who to write a script to do this for me. Ultimately, I would like a list of all missing dates, but even a count of days missing would be great.
Is this possible or am I approaching the issue incorrectly? Any ideas?
Using SQL Server 2012, if it matters.
I am guessing you don't want overlaps either. So, just use lag() and check that it is the date before:
select t.*
from (select t.*,
lag(end_date) over (order by start_date) as prev_end_date
from t
) t
where start_date <> dateadd(day, 1, prev_end_date)

Find the minute difference between 2 date time

I need to get the difference between 2 date time in minutes(Time difference in minutes). And the last difference will be calculated based on 6 PM of every date.
Sample data: need result of last column
User_Name Date Time difference in minutes
User 1 1/1/06 12:00 PM 30
user 2 1/1/06 12:30 PM 315
user 3 1/1/06 5:45 PM 15
Here the date will be always in same date and the last user date difference calculated based on default value 6PM. Assuming the dates of any user will not cross 6PM time.
Please suggest how to write the query for the same.
You could use the lead window function.
I assume your table is called mytable and the date column is mydate (it is a bad idea to call a column Date as it is a reserved word).
select user_name,
round((lead(mydate, 1, trunc(mydate)+18/24)
over (partition by trunc(mydate) order by mydate)
- mydate) *24*60) as difference
from mytable
I found the solution.. if its not correct let me know
SELECT User_name,created_date,
trunc(to_number((cast(nvl(lead (created_date,1) OVER (ORDER BY created_date),TRUNC(SYSDATE) + (19/24)) as date) - cast(created_date as date)))*24*60) as difference
FROM users;

Grouping by similar categories over time

I looked around for awhile, but couldn't find anything.
I have a table that looks like this:
DATE | Shift | Parts Used
1/1/15 1:15.....1........1
1/1/15 2:06.....1........2
1/1/15 3:45.....1........3
1/1/15 7:33.....2........1
1/1/15 8:14.....2........2
1/1/15 9:00.....2........3
1/1/15 23:01....1........1
1/1/15 23:55....1........2
I would like to group by each individual shift. UNFORTUNATELY shift one can sometimes end on a monday morning and start again on monday night (sometimes our twelve hour shifts are not exactly 12 hours). Is there a way I can group by shifts individually, essentially grouping by shift until shift changes even if my day is the same (my actual column contains a time too)? I could write a loop to analyze the data, but getting it from sql would be great.
The date is orders the rows. Shifts cannot overlap.
Hopefully my result would be something like
DATE | Shift | AVG parts used
1/1/15.....1........2
1/1/15.....2........2
1/1/15.....1........1.5
Edit****** Worst case scenario with expected results
DATE | Shift | AVG parts used
1/1/15.....1........1.8
1/1/15.....2........2
I'm assuming that shift 1 is suppose to start at midnight and shift 2 starts at noon, but its sometimes off by some amount of time. This query should work if those assumptions are true. I've made a variable called #ShiftFudgeHours to account for how off the shift start times usually are. Adjust that based on your numbers. From your sample 1 hours looks sufficient, but you could easily increase it.
declare #shiftFudgeHours int = 1
select convert(date, DATEADD(hh, #shiftFudgeHours, [date]) ) as [date]
,[shift]
,avg(convert(float, parts)) as AvgParts
from Table1
group by convert(date, DATEADD(hh, #shiftFudgeHours, [date]) ), [shift]
order by convert(date, DATEADD(hh, #shiftFudgeHours, [date]) ), [shift]

SQL - Query events data for current quarter

I have a course calendar events table as follows (showing only a few records for simplicity):
calendarItemID classID startDate startTime endTime
----------------------------------------------------------
1 1 2011-11-24 7pm 9pm
2 2 2011-11-02 7pm 9pm
3 1 2011-11-25 7pm 9pm
I need a query that returns courses for the UPCOMING QUARTER (not the current quarter). Is there a SQL function that can help and/or is this a case of working out the dates in the current quarter and seeing if StartDate fits within those dates. I'm looking for the most elegant way if possible.
Thanks in advance!
Paul
Straightforward, but slow approach :
WHERE DATEPART(qq,startDate) = DATEADD(qq, 1,GETDATE()) AND YEAR(startDate) =
YEAR(DATEADD(qq, 1,GETDATE()))
By slow I mean that even if you have an index on (startDate) it won't be used.
The better solution is to get start_date and end_date for the next quarter. I can see a number of ways to do so. For instance, you can create 2 scalar UDF that returns start_date and end_date respectively. You can also create 1 table-valued function that returns 1 row with 2 columns and then join it. Finally, you can just create a lookup table and manually enter start/end date for next couple of years.
Create a table called say Quarters with a useful ID say YYYYQQ, and a start and end date, then it's a simple join.