【问题标题】:Runing total - found the date the running total is X运行总计 - 找到运行总计为 X 的日期
【发布时间】:2020-02-07 10:01:41
【问题描述】:

我需要找出哪些玩家 (CID) 的存款总额为 100 或更多,以及他们达到该金额的确切日期。

存款表:

CID        DATE        Deposit_Amount
===        =====       ===============
1234       1/6          20
2345       5/6          30
1234       16/6         1
1234       18/6         50
3456       19/6         18
1234       25/6         150 
2345       31/7         50
2345       1/8          18
3456       1/9          50 
1234       5/9          23
3456       5/10         33

答案应该是:

CID    Date
===    ====
1234   25/6
3456   5/10

我尝试使用以下查询,但我不知道如何找到用户达到 100 岁及以上的确切日期

SELECT [CID]
      ,[Date]
      ,deposit 
      ,SUM([Deposit])OVER(PARTITION BY CID ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Total_deposit
  FROM [ISC_RAS_CD_MAXDB].[dbo].[Deposits]

有什么建议吗? 谢谢!

【问题讨论】:

    标签: sql tsql window-functions


    【解决方案1】:

    考虑:

    select cid, min(date)
    from (
        select t.*, sum(deposit_amount) over(partition by cid order by date) sum_deposit_amount
        from mytable t
    ) t
    where sum_deposit_amount >= 100
    group by cid
    

    子查询在date 上对每个ciddeposit_amount 进行窗口总和;然后外部查询按cid聚合,并选择窗口和等于或大于100的最小值。

    【讨论】:

      【解决方案2】:

      您可以在没有聚合的情况下执行此操作——假设值始终为正:

      select cid, date
      from (select t.*,
                   sum(deposit_amount) over(partition by cid order by date) sum_deposit_amount
            from mytable t
           ) t
      where sum_deposit_amount >= 100 and
            sum_deposit_amount - deposit_amount < 100;
      

      这应该比外部聚合更有效。此外,您可以从最先传递该值的行中恢复更多列。

      【讨论】:

        猜你喜欢
        • 2017-03-25
        • 1970-01-01
        • 2015-03-30
        • 2022-09-30
        • 1970-01-01
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        相关资源
        最近更新 更多