postgresql 计算客户端每周的最晚订单日期(postgres)[已关闭]

jxct1oxe  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(141)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

4天前关闭。
Improve this question
我有一个客户订单表,为了简化,假设结构是client_id -- order_date
我需要得到一个表,其中包含每周有多少客户处于1-2周的流失(1-2周没有下订单),3-4周的流失(3-4周没有下订单)等数据,结构为week -- count of clients in 1-2 week churn -- count of clients in 3-4 week churn
会很感激任何想法如何做到这一点。

ax6ht2ek

ax6ht2ek1#

CREATE TABLE corder (cid INT, orderdate TIMESTAMP);

INSERT INTO corder(cid, orderdate) VALUES
(1, '2023-06-01'),
(1, '2023-05-01'),
(2, '2023-04-01'),
(2, '2023-03-01'),
(3, '2023-05-15'),
(3, '2023-01-01'),
(4, '2023-03-01');

您需要首先运行一个groupby查询,以查找每个客户端的最近orderDate,并根据最近的订单下达时间为客户端分配一个类别。

SELECT MAX(cid) AS cid,
  MAX(orderdate) AS lastOrder,
  CASE WHEN NOW()::DATE - MAX(orderdate)::DATE <= 14 THEN 'CHURN-1-2'
       WHEN NOW()::DATE - MAX(orderdate)::DATE <= 28 THEN 'CHURN-3-4'
       ELSE 'CHURN-MAX'
  END AS Churn
  FROM 
      corder
  GROUP BY cid

然后,您可以在公共表表达式中使用此查询,以便可以查询这些结果,将它们分组到“流失”类别中,并为每个“流失”类别选择客户端计数。

WITH cte AS(
  SELECT MAX(cid) AS cid,
  MAX(orderdate) AS lastOrder,
  CASE WHEN NOW()::DATE - MAX(orderdate)::DATE <= 14 THEN 'CHURN-1-2'
       WHEN NOW()::DATE - MAX(orderdate)::DATE <= 28 THEN 'CHURN-3-4'
       ELSE 'CHURN-MAX'
  END AS Churn
  FROM 
      corder
  GROUP BY cid)
 SELECT
    MAX(Churn) As Churn,
    COUNT(*) AS Clients
 FROM 
    cte
 GROUP BY
    Churn
 ORDER By Churn;

相关问题