繁体   English   中英

SQL-带条件的分钟(日期)

[英]SQL - min(date) with conditionals

我们开展了一项促销活动,用户可以免费获得他们的第一个订阅订单。 当用户使用促销时,价格= $ 0.00。 我对示例A中的数据感兴趣。

示例A-用户50从促销开始,持续了两个月

order_id  user_id    price    created_at
    1        50       0.00    2018-01-15
    5        50      20.00    2018-02-15
    9        50      20.00    2018-03-15

示例B-用户100已经是一个活跃的订户,他取消了他的帐户并通过促销重新激活, 我不希望计数

order_id  user_id    price    created_at
    2        100      20.00    2018-01-16
    3        100       0.00    2018-01-17
    7        100      20.00    2018-02-17

-这是我的查询-

在此处输入图片说明

这将返回具有多个订单的所有用户

他们至少有一个订单的价格= 0.00

-此数据集返回示例A和示例B

- 我的问题 -

这些数据大多数都是正确的(示例A),但是我想忽略其中的一部分,因为它们使我的数据倾斜(示例B)。 我要删除示例B用户。

我想删除第一流不是促销活动的人。

如何请求他们的第一笔订单价格为0.00? 我在想min(created_at)吗?

您可以使用以下命令获得第一笔订单的时间:

select user_id, min(created_at) as min_ca
from t
group by user_id;

接下来,您可以使用以下方法获得第一笔订单的价格:

select oi.*
from order_items oi join
     (select user_id, min(created_at) as min_ca
      from order_items oi
      group by user_id
     ) ooi
     on oi.user_id = ooi.user_id and oi.created_at = ooi.min_ca
where oi.price = 0.00;

然后,您可以使用joininexists获得所有记录;

select oi.*
from order_items oi join
     order_items oi1
     on oi.user_id = oi1.user_id join
     (select user_id, min(created_at) as min_ca
      from order_items oi
      group by user_id
     ) u1
     on oi1.user_id = u1.user_id and oi1.created_at = u1.min_ca
where oi1.price = 0.00;

您可以使用EXISTS检查价格为零的记录是否没有更早的created_at

SELECT COUNT(*), user_id
FROM Promo
WHERE user_id IN (
    -- Query below yields [user_id]s of users who got the promo
    -- that wasn't a result of a cancellation and re-activation
    SELECT user_id
    FROM Promo p
    WHERE p.price = 0 AND NOT EXISTS (
        -- Look for a record with the same user ID and an earlier date
        -- than p.created_at, which is the date of the promo with 0.00 price
        SELECT *
        FROM Promo pp
        WHERE pp.user_id=p.user_id AND pp.created_at < p.created_at
    )
)
GROUP BY user_id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM