【问题标题】:Struggling with customer SQL query与客户 SQL 查询作斗争
【发布时间】:2021-03-20 05:55:56
【问题描述】:

我正在尝试提取满足以下参数的客户数量:

  • 他们的最后一个订单日期和倒数第二个订单日期之间有 +365 天的间隔
  • 2020 年订购

我正在为两块而苦苦挣扎。老实说,我只是在为整件事而苦苦挣扎。

  1. 如何为特定客户提取倒数第​​二个订单日期,然后使用该日期计算间隔
  2. 如果我需要创建客户表或提取 2 个单独的查询

到目前为止,我的间隔计算是正确的,但它从整列而不是客户中获取最大值。

select datediff(day, select max(ship_date) where ship_date < select max(ship_date) :: date, select max(ship_date) :: date)

我需要一个客户间隔 > 365 的计数 以及 (last_ship_date) 或 max(ship_date) >2020 年 1 月 1 日

【问题讨论】:

  • 如果您使用的是 MySQL 8.x,请使用 LAG()

标签: mysql sql datetime aggregate-functions greatest-n-per-group


【解决方案1】:

我会选择lag():

select customer_id
from (select t.*, 
             lag(ship_date) over (partition by customer_id order by ship_date) as prev_ship_date
             row_number() over (partition by customer_id order by ship_date desc) as seqnum
       from t
      ) t
where seqnum = 1 and
      ship_date >= '2020-01-01' and
      prev_ship_date < ship_date - interval 1 year

【讨论】:

    【解决方案2】:

    你可以使用窗口函数:

    select customer_id
    from (
        select t.*, 
            row_number() over(partition by customer_id order by ship_date desc) rn
        from mytable t
    ) t
    where rn <= 2
    group by customer_id
    having max(ship_date) >= '2020-01-01' 
       and max(ship_date) > min(ship_date) + interval 1 year
    

    这个想法是过滤每个客户的两个最新行。然后,您可以使用聚合来比较日期。

    【讨论】:

    • 这与我所拥有的类似,但需要一种方法来选择 2020 年的第一个订单而不是最大订单。 2020 年有多个订单的客户没有通过,因为倒数第二个订单也将在 2020 年,并且不在我们设置的参数范围内。
    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2021-11-25
    相关资源
    最近更新 更多