具有多个表的SQL队列保留

时间:2020-06-27 15:48:26

标签: sql postgresql business-intelligence

作为同类群组分析的一部分,我正在尝试编写2个查询。

  1. 要获得相对的同类群组(按订阅开始日期进行组织),然后 查看已完成的订单
  2. 按月获取每个队列的队列保留输出

其他说明

  • 订阅表和订单表之间没有直接引用
  • 理想情况下,我希望能够通过其他因素来操纵这些表,例如:
    • 已下2个或更多订单的所有订阅者的群组
    • 从未没有订阅的用户的所有订单的同类

我是原始SQL的新手(通常使用ORM),所以我试图将自己的头围在WITH,子查询等周围。谢谢!!

SQL小提琴,表格和所需的输出如下:

http://www.sqlfiddle.com/#!15/792360

用户

+----+---------+
| id |  name   |
+----+---------+
|  1 | Alice   |
|  2 | Bob     |
|  3 | Charles |
|  4 | Dana    |
+----+---------+

订单

+-----+---------+---------+--------------+
| id  | amount  | user_id |  charged_at  |
+-----+---------+---------+--------------+
|   1 |      80 |       1 | '2020-1-08'  |
|   2 |     100 |       1 | '2020-1-09'  |
|   3 |      80 |       2 | '2020-02-01' |
|   4 |      90 |       3 | '2020-02-10' |
|   5 |      80 |       3 | '2020-03-03  |
+-----+---------+---------+--------------+

订阅

+-----+---------+---------+--------------+
| id  | amount  | user_id |  started_at  |
+-----+---------+---------+--------------+
|   1 |      80 |       1 | '2020-01-08' |
|   2 |     100 |       2 | '2020-02-01' |
+-----+---------+---------+--------------+

所需的输出A

+-----------------------------+----------------+---------+-----------+
| months_since_first_purchase | users*         | ordered | retention |
+-----------------------------+----------------+---------+-----------+
|                           0 |              3 |       3 | 100%      |
|                           1 |              3 |       1 | 33%       |
|                           2 |              1 |       0 | 0%        |
+-----------------------------+----------------+---------+-----------+

* =达到此里程碑的用户,等等。购买时间少于2个月的用户将不在自首次购买行起的3个月内

所需的输出B

+---------+------+--------+----------+-----------+
| cohort  | size | months | retained | retention |
+---------+------+--------+----------+-----------+
| Jan '20 |    1 |      0 |        1 | 100%      |
| Jan '20 |    1 |      1 |        0 | 0%        |
| Jan '20 |    1 |      2 |        0 | 0%        |
| Feb '20 |    2 |      0 |        2 | 100%      |
| Feb '20 |    2 |      1 |        1 | 50%       |
| Mar '20 |    0 |      0 |        0 | 0%        |
+---------+------+--------+----------+-----------+

0 个答案:

没有答案