Here is an easier approach.DECLARE @Sample TABLE ( theTime DATETIME NOT NULL, theMachine CHAR(2) NOT NULL );INSERT @Sample ( theTime, theMachine )VALUES ('20130805 10:12:00', 'M1'), ('20130805 10:15:00', 'M1'), ('20130805 10:20:00', 'M1'), ('20130805 10:11:00', 'M2'), ('20130805 10:15:00', 'M2'), ('20130805 10:16:00', 'M2'), ('20130805 10:17:00', 'M2'), ('20130806 11:12:00', 'M1'), ('20130806 11:42:00', 'M1'), ('20130806 12:02:00', 'M1');-- BandiWITH Cte AS (SELECT DATEADD(DD, 0, DATEDIFF(DD, 0, theTime)) Times, theMachine, theTime AS TimePortion FROM @Sample )SELECT c1.Times, c2.theMachine, MAX(DATEDIFF(MI,c1.TimePortion,c2.TimePortion))FROM cte c1JOIN Cte c2 on c1.Times = c2.Times AND c1.theMachine = c2.theMachineGROUP BY c1.Times, c2.theMachine-- SwePesoSELECT DATEADD(DAY, DATEDIFF(DAY, 0, theTime), 0), theMachine, DATEDIFF(MINUTE, MIN(theTime), MAX(theTime))FROM @SampleGROUP BY theMachine, DATEDIFF(DAY, 0, theTime);
However, both approaches will only work as long there is only one sequence per day.What about this sample data? What is your expected output from that?INSERT @Sample ( theTime, theMachine )VALUES ('20130805 10:12:00', 'M1'), ('20130805 10:15:00', 'M1'), ('20130805 10:20:00', 'M1'), ('20130805 10:11:00', 'M2'), ('20130805 10:15:00', 'M2'), ('20130805 10:16:00', 'M2'), ('20130805 10:17:00', 'M2'), ('20130805 19:12:00', 'M1'), ('20130805 19:42:00', 'M1'), ('20130805 20:02:00', 'M1');
I would expect that output to be20130805 M1 5820130805 M2 6
Am I correct?
Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA