【问题标题】:SQL get the first date the condition existsSQL获取条件存在的第一个日期
【发布时间】:2020-10-16 21:02:39
【问题描述】:

我有一个收藏表: subscription_id、transaction_date_est、start_date_est、end_date_est、transaction_id、invoice_number、user_id、transaction_amount、plan_code、transaction_type

我有购买订阅的用户,我为每个订阅生成一个订阅 ID。每个订阅都有 1 到多个发票。 对于每个订阅,我尝试使用窗口函数查找用户何时通过了 100 美元的累积金额。 我的预期结果:subscription_id、transaction_date

我试过了:

SELECT subscription_id, MAX(date) transaction_date
FROM (SELECT subscription_id, 
SUM(usd_price) LAG (partition by subscription_id
ORDER BY first_transaction_date ASC) AS total
GROUP BY(current_period_started_at)
HAVING BY total >= 100
ORDER BY usd_price)

但我没有成功提取用户超过 100 美元的第一个日期。

【问题讨论】:

    标签: sql date select sum window-functions


    【解决方案1】:

    我想你想要:

    select c.*
    from (
        select c.*, sum(usd_price) over((partition by subscription_id order by transaction_date) sum_usd_price
        from collections c
    ) c
    where sum_usd_price >= 100 and sum_usd_price - usd_price < 100
    

    【讨论】:

    • 谢谢,为什么要检查 sum_usd_price - usd_price
    • @ronkolel:此过滤器会在超过阈值的 第一 行上进行过滤。
    猜你喜欢
    • 2018-01-17
    • 2014-12-14
    • 2022-06-11
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多