-3

我正在寻找一些优雅的 SQL 代码来阅读这个

在此处输入图像描述

并创建这个

在此处输入图像描述

当给定@interval(分钟整数)参数时,在这种情况下为 30 分钟间隔。

需要根据第一个表计算登录的时间量,并每隔 30 分钟将其放入第二个表中。

RDMBS 是 MS SQL 服务器。

非常感谢您提前。

4

3 回答 3

2

通常,要将特定的日期时间值分配给分区,这是简单的日期算术:

declare @moment_in_time           datetime = current_timestamp
declare @today                    datetime = convert(date,@moment_in_time)
declare @bucket_length_in_seconds int      = 30 * 60
declare @buckets_per_day          int      = 24*60*60 / @bucket_length_in_seconds
declare @bucket_number            int      = datediff(second,@today,@moment_in_time)
                                           / @bucket_length_in_seconds
declare @bucket_start_time        datetime = dateadd(second,
                                               @bucket_length_in_seconds
                                               * ( datediff(second,@today,@moment_in_time)
                                                   /
                                                   @bucket_length_in_seconds
                                                 ) ,
                                               @today
                                               )

select moment_in_time    = @moment_in_time ,
       today             = @today ,
       buckets_per_day   = @buckets_per_day ,
       bucket_number     = @bucket_number ,
       bucket_start_time = @bucket_start_time

将您的源表分解为它所覆盖的每个存储桶的一行取决于您。提示:由连续的整数序列组成的序列表,范围从 -1,000,000 到 +1,000,000 有时非常有用。

于 2013-09-17T19:03:53.563 回答
1

假设输入数据存储在一个名为 dbo.inputData 的表中,那么下面的 T-SQL 将为您提供您想要的(并且可以轻松改进!)

create table dbo.outputData
(
    StartDateTime datetime not null,
    EndDateTime datetime not null
);

-- Seed the table
declare @maxDate as datetime =  dateadd(hour, 1, (select max(LoggedOutDateTime) from inputData));
with myCte as
(
    -- Truncate the smallest date to the hour
    select dateadd(hour, datediff(hour,0, min(LoginDateTime)),0) as StartDateTime
    from dbo.inputData
    union all
    select dateadd(minute, 30, StartDateTime)
    from myCte
    where StartDateTime <= @maxDate
)

insert into dbo.outputData(StartDateTime,EndDateTime)
select StartDateTime, dateadd(minute,30,StartDateTime)
from myCte;

-- Now do the actual calculations stuff
with myCte2 as
(
select o.StartDateTime, o.EndDateTime, i.LoginDateTime, i.LoggedOutDateTime,
    case when i.LoggedOutDateTime > o.EndDateTime then o.EndDateTime else i.LoggedOutDateTime end as rangeEnd,
    case when i.LoginDateTime > o.StartDateTime then i.LoginDateTime else o.StartDateTime end as rangeStart
from dbo.outputData as o
inner join dbo.inputData as i
    on i.LoggedOutDateTime > o.StartDateTime and 
        i.LoginDateTime < o.EndDateTime
)

select m.StartDateTime, m.EndDateTime, sum(DATEDIFF(SECOND,m.rangeStart, m.rangeEnd)) as secs
from myCte2 as m
group by m.StartDateTime, m.EndDateTime
于 2013-09-17T19:27:14.413 回答
0

(Date1 - date2)*24*60= 您的时间间隔(以分钟为单位)

于 2013-09-17T18:16:27.187 回答