【问题标题】:SQL - Running Calcuation on DateSQL - 在日期上运行计算
【发布时间】:2016-10-12 06:58:18
【问题描述】:

我有一个表,其中包含两个名为“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 以获得包含开始和结束日期的会话列表吗?

提前致谢

【问题讨论】:

    标签: sql sql-server cumulative-sum


    【解决方案1】:

    假设您的表名为 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
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2015-05-08
    • 1970-01-01
    • 2017-03-25
    • 2021-12-14
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多