【问题标题】:VERTICA: Need to calculate rolling DISTINCT COUNTS for past 3 monthsVERTICA:需要计算过去 3 个月的滚动 DISTINCT COUNTS
【发布时间】:2019-12-12 15:39:25
【问题描述】:

以下是我的原始数据

DATE        Product_id Customer_ID
----------------------------
01-JUL-14       60      A
01-AUG-14       45      A
01-SEP-14       45      A
01-SEP-14       50      A
01-OCT-14       30      A
01-JUL-14       60      B
01-AUG-14       45      B
01-SEP-14       45      B
01-OCT-14       30      B

这是我的滚动计数的预期结果

MMYY     Distinct   Customer
         Product
-------------------------
JUL-14      1       A
AUG-14      2       A
SEP-14      3       A
OCT-14      3       A
JUL-14      1       B
AUG-14      2       B
SEP-14      2       B
OCT-14      2       B

我需要它的工作方式是,对于每个 MMYY,我需要回顾 3 个月,并为每个客户计算不同的产品 产品可以重复。而且一个客户在同一个月内可以拥有超过 1 件产品。

通常我会这样写查询

SELECT
  customer_ID, 
  T.Date as MMYY,
  COUNT(DISTINCT Product_id)
    OVER (PARTITION BY customer_ID ORDER BY T.Date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
    AS Last_3_month_count
    FROM T

但问题是我们不能使用 COUNT(DISTINCT Product_id) 它会报错。 建议我用其他方法来解决这个问题。

【问题讨论】:

    标签: sql vertica vsql


    【解决方案1】:

    更新答案

    您可以按如下方式运行查询

        select to_char(b.date,'MM-YY') as mm_yy
              ,count(distinct b.product_id)
              ,b.customer_id
          from raw_data a
          join raw_data b
            on a.customer_id=b.customer_id
           and b.date>=add_months(a.date,-2)
           and b.date<=a.date
      group by to_char(b.date,'MM-YY')
              ,b.customer_id
    

    如果 vertica 允许在选择中进行选择,那么可以使用它

    select to_char(b.date,'MM-YY') as mm_yy
          ,(select count(distinct product_id)
              from raw_data a
             where a.customer_id=b.customer_id
               and a.date>=add_months(b.date,-3)
               and a.date<b.date) as cnt_distinct_pid
           ,b.customer
      from raw_data b
    

    【讨论】:

    • 运行此查询时出现此错误错误:不支持不等式相关子查询表达式
    • 亲爱的,我已经测试了这个查询,但它一直给我每个月的每个客户的计数 1
    【解决方案2】:

    我找到了我的解决方案 这给了我想要的结果集。

    select to_char(a.date,'MM-YY') as mm_yy
              ,count(distinct b.product_id)
              ,b.customer_id
          from raw_data a
          join raw_data b
            on a.customer_id=b.customer_id
           and b.date between(add_months(a.date,-2) and a.date)
      group by to_char(a.date,'MM-YY')
              ,b.customer_id
    

    【讨论】:

    • 你的意思是说这个查询得到你想要的结果,而不是为每个 customer_id 得到 count=1
    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多