Hi All,
SQL version:
Lets say I have the database table consist of vehicle trip.
The vehicle trip have start and end for every trip done by the vehicle. How can I get the number of days trip for vehicle done based on the trip done by vehicle. I have done some SQL query based on study but seems like my query need some changes to get the expected result. The expected result should be:
REGISTRATIONNUMBER tripdays
NDS7297 1
NDT2877 3
But I get like below after run the query
REGISTRATIONNUMBER tripdays
NDS7297 1
NDT2877 4
-- DDL and sample data population, start
DECLARE @tbl TABLE (REGISTRATIONNUMBER varchar(255), TRIPSTART datetime, TRIPEND datetime,
MAXSPEED float, IMPACT_COUNT int, TRIP_ID int)
INSERT INTO @tbl (REGISTRATIONNUMBER, TRIPSTART, TRIPEND, MAXSPEED, IMPACT_COUNT, TRIP_ID) VALUES
('NDS7297', '2022-10-30 08:59', '2022-10-30 09:09', 73, 0, 1658361240),
('NDS7297', '2022-10-30 09:29', '2022-10-30 09:37', 84, 0, 1658377595),
('NDT2877', '2022-11-03 11:31', '2022-11-05 11:56', 0, 0, 1658471861),
('NDT2877', '2022-11-05 11:31', '2022-11-05 15:56', 0, 0, 1658471862),
('NDT2877', '2022-11-05 15:56', '2022-11-05 17:56', 0, 0, 1658471863)
;with T1 as(
select REGISTRATIONNUMBER,CONVERT(varchar(100),TRIPSTART,111) as TRIPSTART,
CONVERT(varchar(100), TRIPEND,111) as TRIPEND from @tbl
group by REGISTRATIONNUMBER,CONVERT(varchar(100),TRIPSTART,111),CONVERT(varchar(100), TRIPEND,111)
),T2 as(
select REGISTRATIONNUMBER,sum(DATEDIFF(day,TRIPSTART, TRIPEND) + 1) as tripdays from T1 group by REGISTRATIONNUMBER
)
SELECT * FROM T2