How do I calculate total minutes between start and end times? - sql-server

How do I calculate total minutes between start and end times? The Start/End times columns are nvarchar and I am declaring them as datetime. I'm not sure if that is my first step or not, I am new to SQL and to declaring.
The final goal is to take Total Minutes, subtract Lunch and Recess (both are minutes) and then multiply by 5 to get total instructional minutes for the week per school.
DECLARE #StartTime datetime, #Endtime datetime
SELECT --[School]
[GradeLevel]
,[StartTime]
,[EndTime]
,(#Endtime - #StartTime) AS 'TotalMinutes'
,[Lunch]
,[Resess]
,[Passing]
FROM [dbo].[StartEndTimes]
Current Output:
GradeLevel StartTime EndTime TotalMinutes Lunch Resess Passing
2-5 7:50 14:20 NULL 20 10 NULL
K-5 7:45 14:20 NULL 20 10 NULL
K-5 7:50 14:20 NULL 20 10 NULL

Maybe something like this is what you want?
select (datediff(minute, starttime, endtime) -lunch -recess) * 5 AS TotalInstruct
from YourTable
If you want to sum it up for all rows then try:
select sum((datediff(minute, starttime, endtime) -lunch -recess) * 5) AS TotalInstruct
from YourTable
If you want to get the number of hours per school you would have to include the schoolfield in the query and use it in the group byclause, and then the query becomes this:
select school, sum((datediff(minute, starttime, endtime) -lunch -recess) * 5) AS TotalInstruct
from YourTable
group by school
Sample SQL Fiddle for the above queries.

If all you want is to find the difference between two dates then you can use DATEDIFF function (http://msdn.microsoft.com/en-us/library/ms189794.aspx)
Example:
DECLARE #startdate datetime2
SET #startdate = '2007-05-05 12:10:09.3312722';
DECLARE #enddate datetime2 = '2007-05-04 12:10:09.3312722';
SELECT DATEDIFF(MINUTE, #enddate, #startdate);
If however your values are in string format you need to convert them prior to passing them to the DATEDIFF function.
Example:
DECLARE #starttexttime nvarchar(100)
SET #starttexttime = '7:50'
DECLARE #starttime datetime2
SET #starttime = CONVERT(datetime2, #starttexttime, 0)
DECLARE #endtexttime nvarchar(100)
SET #endtexttime = '17:50'
DECLARE #endtime datetime2
SET #endtime = CONVERT(datetime2, #endtexttime, 0)
SELECT DATEDIFF(MINUTE, #starttime, #endtime);

Related

MS SQL Server Query to Check if Hall is Booked

This query is driving me crazy, any help is appreciated.
I have a table as follows:
CREATE TABLE Bookings
(
Id bigInt IDENTITY(1,1),
hallId bigInt,
startTime smallDateTime,
endTime smallDateTime
)
INSERT INTO Bookings
VALUES (1, '2022-10-03 08:00:00', '2022-10-03 10:00:00')
--Edit( One of my trials so far
DECLARE #startTime AS SmallDateTime = '2022-10-03 08:00:00'
DECLARE #endTime AS SmallDateTime = '2022-10-03 10:0:00'
DECLARE #hallId AS bigInt = 1
SELECT * FROM Bookings WHERE
startTime >= FORMAT(#startTime, 'yyyy-dd-MM HH:mm:ss') OR startTime <= FORMAT(#endTime, 'yyyy-dd-MM HH:mm:ss') AND
endTime >= FORMAT(#startTime, 'yyyy-dd-MM HH:mm:ss') OR endtime <= FORMAT(#endTime, 'yyyy-dd-MM HH:mm:ss')
AND hallId=#hallId
-- Also this Way
DECLARE #startTime AS SmallDateTime = '2022-03-10 08:00:00'
DECLARE #endTime AS SmallDateTime = '2022-03-10 10:0:00'
DECLARE #hallId AS bigInt = 1
SELECT * FROM Bookings WHERE
startTime >= #startTime OR startTime <= #endTime
AND
endTime >= #startTime OR endtime <= #endTime
AND hallId=#hallId
--Edit)
My Datetime format is 'yyyy-MM-dd HH:mm:ss' but it's records are entered in yyyy-dd-MM HH:mm:ss format
So what I want is a query that checks for 2 datetime ranges (say 2022-10-03 08:00:00 - 2022-10-03 10:00:00), if there is a match it returns the data otherwise it returns nothing.
My goal is to check if either of the startTime OR endTime falls within an existing Booking (e.g None of startTime or endTime can't be within '2022-10-03 08:00:00' up to '2022-10-03 10:00:00'), if found, the booking can't precede unless he/she has to alter. I tried between, but seems to work one way and fails another
It would be a plus if someone could check in separately that is to display a specific message/status for startTime and endTime (I mean if the startTime corresponds to existing Booking msg='Select a different start time' and if The endTime corresponds to existing Booking msg='Select a different end time'
Also I tried to check if the difference of startTime and endTime is less then 1 hour.
BWT, I'm using SQL Server 2014 Express
You can do INSERT...SELECT...WHERE NOT EXISTS, then check the rowcount afterwards. To compare for interval overlap, compare one start time with the other end, and the reverse.
Note that you should always specify column names for inserts, and pass values as parameters, not text.
INSERT INTO Bookings (hallId, startTime, endTime)
SELECT #hallId, #startTime, #endTime
WHERE NOT EXISTS (SELECT 1
FROM Bookings b WITH (UPDLOCK) -- needs UPDLOCK to prevent race conditions
WHERE b.hallId = #hallId
AND b.startTime < #endTime
AND b.endTime > #startTime
);
IF ##ROWCOUNT = 0
THROW 50001, N'Overlapping booking exists', 1;
You may want to change to <= if you don't want to allow two intervals to abut.
Thanks to who ever tried to help, I figured it out,
Sometimes all you need is to take a quick break.
I found out that smallDateTime data type was acting crazy, it was swapping the month and the day while inserting in the table
e.g if I Inserted 2022-03-15 20:00:00 it would be recorded as 2022-15-03 20:00:00 and vice-versa
So Here goes what worked for me, It may help someone in the nearer or far future
-- 2022-03-11 13:30:00, 2022-03-11 15:00:00 => sample data 1 in the table
-- 2022-03-11 09:30:00, 2022-03-11 12:30:00 => sample data 2 in the table
DECLARE #startTime AS SmallDateTime = '2022-03-11 15:01:00'
DECLARE #endTime AS SmallDateTime = '2022-03-11 19:30:00'
DECLARE #hallId AS bigInt = 1
SELECT * FROM Bookings WHERE
(startTime BETWEEN #startTime AND #endTime) OR
(endTime BETWEEN #startTime AND #endTime) AND hallId=#hallId

SQL Sever - Datediff, hours, but exclude Saturday/ Sundays

I'm wondering how to calculate the "number of hours" between two timestamps (2016-02-24 17:30:00 and another, for instance) in SQL server- but excluding Saturday and Sunday's full 48 hour period, if crossed.
This isn't quite the same as pure business hours, but sort of. The reason for this is long-winded and unnecessary.
EDIT: I can also say that the end-date will always be during the week. So really ... the "start date" can simply be transmuted to Monday midnight, if on Sat/ Sun ... then maybe a function include the total week count...
DATEDIFF(Week, date, date2) will return the number of week boundaries that are crossed between the two dates. For SQL Server, this means how many Sundays are between the dates (as opposed to the number of 7 day periods are between them). This means, that if you can indeed assume that start and end date will not be a saturday or sunday, you can subtract 48 X DATEDIFF(Week, date, date2) from your normal DATEDIFF call and that should give you what are after.
I would use the below code
declare #NumberOfHours int
declare #StartTime datetime
declare #EndTime datetime
set #StartTime = '2017-02-02 17:30:00.000'
set #EndTime = '2017-02-07 00:00:00.000'
set #NumberOfHours = DATEDIFF(HOUR,#StartTime,#EndTime)
if(datepart(WEEKDAY, #StartTime)=1)
begin
set #NumberOfHours = #NumberOfHours DATEDIFF(HH,#StartTime,#EndTime)%24
end
else if(datepart(WEEKDAY, #StartTime)=7)
begin
set #NumberOfHours = #NumberOfHours - DATEDIFF(HH,#StartTime,#EndTime)%24
set #NumberOfHours = #NumberOfHours - 24
end
else
begin
set #NumberOfHours = #NumberOfHours - datediff(ww,#StartTime,#EndTime)*48
end
print #NumberOfHours
I would use a calendar table (ex. dbo.DateDimension, ref https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/):
CREATE TABLE dbo.DateDimension
(
DateKey INT NOT NULL PRIMARY KEY,
[Date] DATE NOT NULL,
[Day] TINYINT NOT NULL,
DaySuffix CHAR(2) NOT NULL,
[Weekday] TINYINT NOT NULL,
WeekDayName VARCHAR(10) NOT NULL,
IsWeekend BIT NOT NULL,
IsHoliday BIT NOT NULL,
...
)
and, also, following query:
SELECT SUM(
CASE
WHEN dd.[Date] = CONVERT(DATE, #StartDate) THEN DATEDIFF(MINUTE, #StarDate, DATEADD(DAY, 1, dd.[Date]))
WHEN dd.[Date] = CONVERT(DATE, #EndDate) THEN DATEDIFF(MINUTE, dd.[Date], #EndDate)
ELSE 24 * 60 -- Full day
END) / 60 AS SumOfHours
FROM dbo.DateDimension dd
WHERE dd.[Date] >= CONVERT(DATE, #StartDate) AND dd.[Date] <= CONVERT(DATE, #EndDate)
AND dd.IsWeekend = 0
Above query will compute total amount of minutes for requested period of time and then it will divide by 60 to get number of hours.

How to subtract two date as datetime2 format in Sql Server 2008

How can I create a method to subtract two dates and this is equal to in real date as format datetime2(7) in sql server 2008.
For example ,I create this method:
Delete from TblMessage
Where MDateTime<((SELECT TOP (1)MDateTime FROM TblMessage ORDER BY MDateTime DESC)- ('2013-10-04 16:47:56.0000000'))
but it is not working .I want to result of subtract two date like this:
MDateTime1:2013-10-05 16:47:56.0000000
MDateTime2:2013-09-04 16:47:56.0000000
Result:2013-01-01 00:00:00.0000000
Result=MDateTime1-MDateTime2
How can I do this. Thanks...
Perhaps you are looking for this?
select DATEADD( day, datediff(day,GETDATE(), getdate() - 10), GETDATE() ) ;
DATEDIFF(dayofyear,MDateTime1,MDateTime2) AS Result
http://msdn.microsoft.com/en-us/library/ms189794.aspx
DECLARE
#DATE1 DATETIME = '2013-10-05 16:47:56.000',
#DATE2 DATETIME = '2013-09-04 17:37:42.000',
#DATEDIFF AS INT,
#BASEDATE DATETIME;
-- USE WHAT EVER DATE YOU WISH TO BE YOUR BASE DATE
SET #BASEDATE = '1/1/1900';
SET #DATEDIFF = DATEDIFF(SECOND, #DATE2, #DATE1);
SELECT #DATE1,#DATE2,#DATEDIFF, DATEADD(SECOND,#DATEDIFF,#BASEDATE)
Thus a scalar function could be created like this...
CREATE FUNCTION dbo.sf_GetMeasureDate
(
#EndDate DATETIME,
#StartDate DATETIME,
#BaseDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE #DATEDIFF AS INT
SET #DATEDIFF = DATEDIFF(SECOND, #StartDate, #EndDate);
Return DATEADD(SECOND,#DATEDIFF,#BASEDATE)
END
GO
Then within you regular SELECT statement you can call the function as such.
SELECT dbo.sf_GetMeasureDate('2013-10-05 16:47:56.000','2013-09-04 17:37:42.000','1/1/1900')
or within an existing query:
SELECT dbo.sf_GetMeasureDate([fld1],[fld2],'1/1/1900')

Sybase get today result, two way comparison

I don't know how to test the performance of these two way of getting what i want.
select *
from table
where column like '%'+left(getdate(),11)+"%
select *
from table
where
DATEPART (DD, column) = DATEPART (DD, GETDATE())
AND DATEPART (MM, column) = DATEPART (MM, GETDATE())
AND DATEPART (YY, column) = DATEPART (YY, GETDATE())
Typically in SQL you can just loop through executing the statement however many times and calculating the time to execute for each statement. Do this a few times to be sure and compare the results.
declare #startTime datetime
declare #endTime datetime
declare #execution BIGINT
SET #execution = 0
set #startTime = GETDATE()
while (#execution < 1000000)
begin
--TestSyntax goes here
SET #execution = #execution + 1
end
set #endTime = GETDATE()
SELECT DATEDIFF(ms, #endTime, #startTime) AS 'TimeToExecute'
Also know, string comparisons are typically slower in all languages.

datetime to totalminute in sql

How can I get the total minute for sql datetime?
Let's say:
select getdate() from table
In this way, I will get everything, but I only want to get total minute. For eg,
if the time is 07:10:35, I want 430.
How to achieve that?
The value from the field is 01-01-2001 07:10:40
The result I want is 430 ((7*60)+10) only.
Here's a sample:
DECLARE #dt datetime
SET #dt = '01-01-2001 07:10:20'
SELECT DATEDIFF(MINUTE, DATEADD(DAY, DATEDIFF(DAY, 0, #dt), 0), #dt)
(DATEPART(HOUR,GETDATE()) * 60) + DATEPART(MINUTE,GETDATE())
This query will return the number of minutes past midnight.
declare #now datetime = getdate()
declare #midnight datetime = CAST( FLOOR( CAST( #now AS FLOAT ) ) AS DATETIME )
select datediff(mi, #midnight,#now)
The code
CAST( FLOOR( CAST( "yourDateTimeHere" AS FLOAT ) ) AS DATETIME )
converts any datetime to midnight. Use the datediff with the "mi" function to get the number of minutes past midnight.
Use books online for more date and time math

Resources