Hi @jn93
Are these two rows of data reversed?
According to your statement, I thought for a while.
The 'No. of day vehicle is used/ No. of day in the month' column should be the number of days used divided by the total number of days. 'NDS7297' should have been used for a total of one day, while 'NDT2877' should have been used for a total of six days.
So I designed this query, you can try it.
;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
),T3 as(
select REGISTRATIONNUMBER as [Row Labels],
COUNT(TRIP_ID) as [Count of TRIP_ID],
MAX(MAXSPEED) as [Max of MAXSPEED],
DAY(EOMONTH(MIN(CAST(TRIPSTART AS date)))) as monthdays FROM tbl GROUP BY REGISTRATIONNUMBER)
select [Row Labels],[Count of TRIP_ID],[Max of MAXSPEED],
cast(A.tripdays as float)/B.monthdays as 'No. of day vehicle is used/ No. of day in the month'
from T2 as A inner join T3 as B on A.REGISTRATIONNUMBER = B.[Row Labels];
Output:
Best regards,
Percy Tang
If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".