显示给定月份具有销售日期的客户数量和最后一个销售日期大于给定月份的3个月的客户数量

问题描述 投票:1回答:1

[基本上,我的要求是-对于给定的月份,有多少客户有销售日期,然后是给定月份中有多少“这些”客户在给定月份前3个月具有上次销售日期。

我尝试使用滞后函数,但“过去的客人”列始终为我提供空值。

 SELECT datepart(month,["sale date"]) `"Sale_Month",count(distinct 
["user id"]) "Guests",
lag("Guests",4) OVER (ORDER BY "Sale_Month")+
lag("Guests",5) OVER (ORDER BY "Sale_Month")+
lag("Guests",6) OVER (ORDER BY "Sale_Month")+
lag("Guests",7) OVER (ORDER BY "Sale_Month")+
lag("Guests",8) OVER (ORDER BY "Sale_Month")+
lag("Guests",9) OVER (ORDER BY "Sale_Month")+
lag("Guests",10) OVER (ORDER BY "Sale_Month")+
lag("Guests",11) OVER (ORDER BY "Sale_Month")+
lag("Guests",12) OVER (ORDER BY "Sale_Month") "Past Guests"
group by "Sale_Month"
order by "Sale_Month"

我的预期输出是按月显示的当月来宾数量,以及这些销售者中最后一次销售的日期比给定月份早3个月的来宾数量>]

预期结果:

Sale_Month     Guests      Past_Guests

  June         1,200          110
  July         1,800          130
  Aug          1,500          140

实际结果:

Sale_Month     Guests      Past_Guests

  June         1,200          null
  July         1,800          null
  Aug          1,500          null

[基本上,我的要求是-在给定的月份中,有多少客户具有销售日期,然后是在给定月份中存在的“这些”客户中有多少人具有先前的销售日期3 ...

sql amazon-redshift amazon window-functions lag
1个回答
0
投票

您似乎想要这样的东西:

select sale_month, count(distinct user_id) as guests,
       count(distinct case when min_sale_date < sale_date - interval '3 month' then user_id end) as old_guests
from (select t.*,
             min(sale_date) over (partition by user_id) as min_sale_date
      from t
     ) t
group by sale_month
order by sale_month;
© www.soinside.com 2019 - 2024. All rights reserved.