识别已连续N个月订购> = N美元的用户

时间:2018-03-09 16:49:58

标签: sql postgresql

我正在寻找一个查询,该查询返回一个帐户的结果集,该帐户已连续六个月每月至少订购250美元。任何指导都将不胜感激。

SELECT DATE_TRUNC ('month',order_date)::date as order_month
       ,account_name
       ,account_id
       ,SUM(order_amount) as monthly_spend
FROM order_table
WHERE order_date::date >= current_date - interval '6 months'
GROUP BY 1,2,3

1 个答案:

答案 0 :(得分:1)

  

那些连续六个月每月订购至少250美元的人。

我想到了聚合。让我也将月份与日历月份保持一致(这似乎是对#34;过去六个月和#34的最可能的解释)。

想法是过滤到> = $ 250的月份,然后确保有六个月。

SELECT account_name, account_id, COUNT(*) as num_months,
      SUM(monthly_spend) as total_spend
FROM (SELECT DATE_TRUNC('month', order_date)::date as order_month,
             account_name, account_id, SUM(order_amount) as monthly_spend
      FROM order_table
      WHERE order_date::date >= date_trunc('month', current_date) - interval '6 months' AND
            order_date::date <  date_trunc('month', current_date)
      GROUP BY 1, 2, 3
      HAVING monthly_spend >= 250
     ) ma
GROUP BY 1, 2
HAVING COUNT(*) = 6;