Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hey,I have a table which contains speed samples of car. the table has the following structure:DateTime | Speed07:50:00 | 8508:00:00 | 9008:01:00 | 9208:03:00 | 9608:10:00 | 88and so on..Pay attention that the sample's interval is not constant.Assume that if sample was taken at 08:00:00 at speed of 95 KPH and the next one was taken at 08:10:00 at speed of 88 KPH - the car speed for these 10 minutes was 95.I need a query which summarize the total time the car was at speed of minimum 90 KPH.
[code]-- SwePesoWITH cteSource(grp, _Time, Speed, Yak)AS ( SELECT ROW_NUMBER() OVER (ORDER BY s._Time) - ROW_NUMBER() OVER (PARTITION BY SIGN(s.Speed / 90) ORDER BY s._Time) AS grp, s._Time, s.Speed, f._Time AS Yak FROM @Sample AS s OUTER APPLY ( SELECT TOP(1) x._Time FROM @Sample AS x WHERE x._Time > s._Time ORDER BY x._Time ) AS f)SELECT _Time, Speed, CASE WHEN Speed < 90 THEN NULL ELSE DATEDIFF(SECOND, _Time, MAX(Yak) OVER (PARTITION BY grp)) END AS SecondsOver90FROM cteSource;[/code]Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA