I am working on a rent system database where a car is given on rent. I need to calculate the (sum of time difference) total time of loan for a car in the given date time range for only working hours and excluding weekend.
Examples to clarify the scenarios
our given date range in where clause is 1/02/17 and 5/2/17
Joe books a car on 01/02/2017 at 9am and returns it at 5pm on 01/02/2017 … 8 hour booking included.
our given date range in where clause is 19/02/17 and 20/2/17
Trish books car on 19/02/2017 at 9am and returns it at 5pm on 21/02/2017 … 16 hour booking included only (ie. 19th & 20th), as the 3rd day falls outside our Date Range end point of 20/02/2017.
our given date range in where clause is 1/02/17 and 5/2/17
Tom books car on 31/01/2017 at 9am and returns it at 12pm on 01/02/2017 … 3 hour booking included only (ie. ½ day on 1st Feb), as the the 1st day (ie. 31st Jan) falls outside our Date Range starting point of 01/02/2017
If any of the column values differ (ie. Company Name, Loan Vehicle Registration, Service Advisor, or Drivers Number Plate)then, that will be a unique row. But if those column are all the same and the only difference is the booking date (ie. if Joe books same car out twice within the Date Range period, using the same Company, Service Advisor, and Drivers Number Plate), then that should be grouped/calculated as one record line.
My current stored procedure is
ALTER PROCEDURE [dbo].[bookingAnalysis]
@from_date nvarchar(50)=NULL,
@to_date nvarchar(50)=NULL
AS
BEGIN
SET NOCOUNT ON;
Select cmp.CompanyName,v.NumberPlate as Loan_Vehicle_Registration,m.ModelDescription as Vehicle_Description,
cnt.FirstName,cnt.LastName,DATEDIFF(HOUR,b.DueOutDate,b.ActualReturnedDate)as
Duration_of_Loan,b.bookingID,b.DriversNumberPlate from Bookings as b
inner join Companies as cmp on b.AssignedCompanyID=cmp.CompanyID
inner join Vehicles as v on v.VehicleID=b.VehicleID
inner join Models as m on m.ModelID=v.ModelID inner join Contacts
cnt on cnt.ContactID=b.ContactID where b.DueOutDate>= @from_date and b.ActualReturnedDate<= @to_date
END
Currently I am getting datediff between b.DueoutDate and b.ActualReturnDate