从具有某些条件的 SingleDateTime 列导出 StartDateTime 和 EndDateTime-SQL 专家

Derive StartDateTime and EndDateTime from SingleDateTime column with some condition-SQL EXPERTS

为了更好地理解,请找到所附图片 (For detailed information please click here)

条件:

  1. value_string/Value_Float 列字段值存在即大于 0,视为 Start_DateTime,下一行具有相同的值不考虑该值只是忽略该字段。否则下一行包含不同的值,将其视为 start_datetime.

  2. If value_string/Value_Float column field value 0,consider as End_Time,In every Group if First Value 0 don't consider.after the start_Datetime到达 0 视为 End_dateTime

  3. 如果该组未以 0(End_dateTime) 结束,则将该字段显示为 'Null'(示例组 C)

来源Table:

想要的结果

创建Table

CREATE TABLE [dbo].[Activity]
( 
    [DateTime] [datetime] NULL,     
    [Group] [nvarchar](255) NULL,   
    [Value_String] [float] NULL,    
    [Value_Float] [float] NULL 
)

插入值

Insert INTO [Activity] VALUES ( '2021-06-23 11:32.000','A','0',0)
Insert INTO [Activity] VALUES ( '2021-06-23 12:13.000','A','1',1)
Insert INTO [Activity] VALUES ( '2021-06-23 17:25.000','A','0',0)
Insert INTO [Activity] VALUES ( '2021-06-24 07:32.000','A','12',12)
Insert INTO [Activity] VALUES ( '2021-06-24 11:30.000','A','0',0)
Insert INTO [Activity] VALUES ( '2021-06-23 05:02.000','B','15',15)
Insert INTO [Activity] VALUES ( '2021-06-23 06:20.000','B','0',0)
Insert INTO [Activity] VALUES ( '2021-06-23 08:16.000','B','5',5)
Insert INTO [Activity] VALUES ( '2021-06-24 19:12.000','B','5',5)
Insert INTO [Activity] VALUES ( '2021-06-24 23:29.000','B','0',0)
Insert INTO [Activity] VALUES ( '2021-06-23 11:42.000','C','0',0)
Insert INTO [Activity] VALUES ( '2021-06-23 13:20.000','C','4',4)
Insert INTO [Activity] VALUES ( '2021-06-23 16:15.000','C','0',0)
Insert INTO [Activity] VALUES ( '2021-06-24 17:52.000','C','4',4)
Insert INTO [Activity] VALUES ( '2021-06-24 23:12.000','C','4',4)
Insert INTO [Activity] VALUES ( '2021-06-23 11:32.000','D','17',17)
Insert INTO [Activity] VALUES ( '2021-06-23 13:47.000','D','15',15)
Insert INTO [Activity] VALUES ( '2021-06-23 16:48.000','D','0',0)
Insert INTO [Activity] VALUES ( '2021-06-24 17:32.000','D','24',24)
Insert INTO [Activity] VALUES ( '2021-06-24 19:32.000','D','0',0)

select min([Datetime]) as startdt, max(next0datetime) as enddt, [Group], Value_String, Value_Float
from
(
select *,  sum(addme) over(partition by [Group] order by [DateTime]) as grpid
from
(
select *,
min(case when Value_String = '0' then [Datetime] end) over(partition by [Group] order by [DateTime] rows between 1 following and unbounded following)
as next0datetime,
case when Value_String <> lag(Value_String) over(partition by [Group] order by [DateTime]) then 1 else 0 end as addme
from dbo.Activity
) as a
) as g
where Value_String <> '0' 
group by [Group], grpid, Value_String, Value_Float
order by [Group], startdt, enddt;