SQL - 在日期运行计算

时间:2016-10-12 06:58:19

标签: sql sql-server running-total

我有一个包含两列名为'AllocationTimestamp'和'DeallocationTimestamp'的表以及一个名为'UserId'的列

可以在给定时间分配许多用户,但是一旦分配了第一个用户,会话就会开始,当他们没有分配用户时,会话结束。

示例是:

User1: 2016-01-01 -> 2016-01-05
User2: 2016-01-02 -> 2016-01-10
User1: 2016-01-07 -> 2016-01-15
User3: 2016-01-03 -> 2016-01-08

User1: 2016-01-20 -> 2016-01-22
User2: 2016-01-20 -> 2016-01-25
User1: 2016-01-25 -> 2016-01-28

这应该给两个会议,其中一个开始于2016-01-01,结束于2016-01-15,另一个开始于2016-01-20,结束于2016-01-28

请注意,当用户尚未解除分配时,“DeallocatedTimestamp”为空。

有人可以帮助我将一些SQL放在一起以获取包含开始日期和结束日期的会话列表吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

假设您的表名为Sessions,此脚本可能会为您提供一个起点...

with BaseData as
(
    select *
        , row_number() over(order by AllocationTimestamp asc) as SeqNo
    from Sessions
)
,Data(UserID, AllocationTimestamp, DeallocationTimestamp, SeqNo, SessionNo) as
(
    select BD.*
        , 1
    from BaseData as BD
    where (BD.AllocationTimestamp=(select min(AllocationTimestamp) from Sessions))

    union all

    select BD.*
        , D.SessionNo + case when (BD.AllocationTimestamp between D.AllocationTimestamp and coalesce(D.DeallocationTimestamp,current_timestamp)) then 0 else 1 end
    from BaseData as BD
    join Data as D
        on(BD.SeqNo-1=D.SeqNo)

)

select SessionNo
    ,min(AllocationTimestamp)
    ,case when max(coalesce(DeallocationTimestamp,current_timestamp))=current_timestamp then null else max(DeallocationTimestamp) end
from Data
group by SessionNo