Somebody smarter than me may be able to come up with a more elegant solution. This is how I solve this type of problem. Note that I return the minutes value for
load_1
=0 and for
load_1
=1 as columns in one row rather than as two separate rows.
Create a table
USE [Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TSI_T_ClientDetailMaster](
[Client_Id] [nvarchar](50) not null,
[Load_1] [int] NOT NULL,
[RTC] [datetime] NOT NULL
) ON [PRIMARY]
GO
Populate the table
truncate table tsi_T_ClientDetailMaster;
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 16:10');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 17:00');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 17:10');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 17:20');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 17:30');
insert into tsi_T_ClientDetailMaster values('TS1733',0,'8/21/2014 17:40');
insert into tsi_T_ClientDetailMaster values('TS1733',0,'8/21/2014 17:50');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 18:00');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 18:10');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 18:20');
insert into tsi_T_ClientDetailMaster values('TS1733',1,'8/21/2014 18:40');
Transact-SQL to compute the minutes where load_1=0 and where load_1=1
You could easily turn this into a Stored Procedure.
Declare @load BIT
Declare @RTC DateTime
Declare @lastLoad BIT
Declare @BeginRTC DateTime
Declare @FIRST_TIME BIT
Declare @Time0 INT = 0
Declare @Time1 INT = 0
Declare @Client_ID NVARCHAR(50) = 'TS1733'
Declare @SelectDate Date = '2014-08-21'
Declare myRows CURSOR FOR SELECT load_1, rtc from TSI_T_ClientDetailMaster Where Client_Id=@Client_Id and CONVERT(DATE,RTC)=@SelectDate Order By Client_Id,RTC
SET @FIRST_TIME=1
OPEN myRows
FETCH NEXT FROM myRows INTO @load, @RTC
WHILE @@FETCH_STATUS = 0
BEGIN
IF @FIRST_TIME=1
BEGIN
SET @FIRST_TIME=0
SET @lastLoad=@load
SET @BeginRTC=@RTC
END
ELSE
BEGIN
IF NOT (@lastLoad=@load)
BEGIN
If @lastLoad=0
BEGIN
SET @Time0=@Time0 + DateDiff(MINUTE,@BeginRTC,@RTC)
SET @BeginRTC=@RTC
SET @lastLoad=@load
END
ELSE
BEGIN
SET @Time1=@Time1 + DateDiff(MINUTE,@BeginRTC,@RTC)
SET @BeginRTC=@RTC
SET @lastLoad=@load
END
END
END
FETCH NEXT FROM myRows INTO @load, @RTC
END
If @lastLoad=0
BEGIN
SET @Time0=@Time0 + DateDiff(MINUTE,@BeginRTC,@RTC)
END
ELSE
BEGIN
SET @Time1=@Time1 + DateDiff(MINUTE,@BeginRTC,@RTC)
END
CLOSE myRows
DEALLOCATE myRows
Select @Client_ID AS Client_Id,@Time0 AS Time_0,@Time1 AS Time_1
The results
Client_Id Time_0 Time_1
TS1733 20 130