作为同类群组分析的一部分,我正在尝试编写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% |
+---------+------+--------+----------+-----------+