Reputation: 3617
For insight in vehicle rental versus vehicle occupancy / empty times, i want to create a time matrix (for use in a SSAS Cube).
Below the available data for the rental part:
Now i would like to pivot this data to the following result. Showing the amount of minutes for vehicle rental per hour.
Any help on the correct SQL syntax to achieve this result would be great.
Upvotes: 2
Views: 308
Reputation: 1464
CREATE FUNCTION [dbo].GetTime (@Start TIME, @End TIME)
RETURNS @TableTime TABLE(_HH TIME, _MM INT)
AS
BEGIN
WHILE DATEPART(HH, @Start) <= DATEPART(HH, @End)
BEGIN
INSERT INTO @TableTime
SELECT DATEPART(HH, @Start), 60
SET @Start = CAST(DATEADD(HH,1,@Start) AS TIME)
END
UPDATE @TableTime SET _MM = 60 - DATEPART(MINUTE, @Start) WHERE _HH = DATEPART(HH, @Start)
UPDATE @TableTime SET _MM = DATEPART(MINUTE, @End) WHERE _HH = DATEPART(HH, @End)
END
SELECT DATE, VEHICLE CROSS APPLY GetTime(Starttime, Endtime) G
Upvotes: 0
Reputation: 16958
I think you can use CTE to collect 24 hours and use a CASE
to achieve your expected result like this:
;WITH HoursAll(H) AS (
SELECT 0
UNION ALL
SELECT H + 1
FROM HoursAll
WHERE H < 23
)
SELECT t.date, t.vehicle, CAST((CAST(ha.H As varchar(10)) + ':00') As time) as [hour]
, CASE
WHEN ha.H = DATEPART(HOUR,t.starttime) THEN 60 - DATEPART(MINUTE,t.starttime)
WHEN ha.H = DATEPART(HOUR,t.endtime) THEN DATEPART(MINUTE,t.endtime)
ELSE 60
END
FROM HoursAll ha
JOIN yourTable t ON ha.H BETWEEN DATEPART(HOUR,t.starttime) AND DATEPART(HOUR,t.endtime);
Upvotes: 3