尝试进行同类群组分析我只有以下一张表,
如何使用MySQL查询用户群组,按月分组,现在我这样做了,
我写的SQL是以下内容,但仅按天,并且该列已定义
SELECT
first_day p,
sum(case when by_day = 0 then 1 else 0 end) day_0,
sum(case when by_day = 1 then 1 else 0 end) day_1,
sum(case when by_day = 2 then 1 else 0 end) day_2,
sum(case when by_day = 3 then 1 else 0 end) day_3,
sum(case when by_day = 4 then 1 else 0 end) day_4,
sum(case when by_day = 5 then 1 else 0 end) day_5,
sum(case when by_day = 6 then 1 else 0 end) day_6,
sum(case when by_day >= 7 then 1 else 0 end) day_7plus
from (
select customer_id, dtime, first_day, DATEDIFF(dtime,first_day) as by_day
from (
select o.customer_id, o.dtime, o2.first_day
from (
select customer_id, STR_TO_DATE(create_time, "%Y-%m-%d") as dtime
from `pb_order`
group by customer_id, dtime
) o
left join
(
select customer_id, min(dtime) as first_day
from (
select customer_id,
STR_TO_DATE(create_time, "%Y-%m-%d") as dtime
from `pb_order`
group by customer_id, dtime
) op
group by customer_id
) o2 on o2.customer_id = o.customer_id
) e
) f group by p
这是查询结果,列是天数。
+------------+-------+-------+-------+-------+-------+-------+-------+-----------+
| p | day_0 | day_1 | day_2 | day_3 | day_4 | day_5 | day_6 | day_7plus |
+------------+-------+-------+-------+-------+-------+-------+-------+-----------+
| 2017-12-26 | 47 | 8 | 5 | 4 | 5 | 3 | 2 | 35 |
| 2017-12-27 | 49 | 3 | 3 | 4 | 2 | 2 | 1 | 109 |
| 2017-12-28 | 25 | 4 | 2 | 2 | 0 | 2 | 1 | 61 |
| 2017-12-29 | 41 | 6 | 4 | 6 | 3 | 2 | 3 | 159 |
| 2017-12-30 | 38 | 2 | 3 | 0 | 0 | 0 | 2 | 41 |
| 2017-12-31 | 50 | 2 | 0 | 1 | 0 | 1 | 1 | 21 |
| 2018-01-01 | 76 | 4 | 7 | 0 | 2 | 3 | 5 | 117 |
| 2018-01-02 | 45 | 7 | 8 | 1 | 1 | 1 | 2 | 165 |
| 2018-01-03 | 23 | 4 | 2 | 1 | 1 | 2 | 1 | 135 |
| 2018-01-04 | 18 | 2 | 0 | 1 | 4 | 5 | 1 | 109 |
| 2018-01-05 | 38 | 2 | 2 | 1 | 1 | 1 | 2 | 55 |
+------------+-------+-------+-------+-------+-------+-------+-------+-----------+
但是我想查询用户每月计数和分组的结果,例如:
+---------+---------+---------+---------+---------+---------+---------+---------+
| month | 2017/12 | 2018/01 | 2018/02 | 2018/03 | 2018/04 | 2018/05 | 2018/06 |
+---------+---------+---------+---------+---------+---------+---------+---------+
| 2017/12 | 54 | 32 | 17 | 23 | 21 | 34 | 16 |
| 2018/01 | 0 | 47 | 21 | 23 | 11 | 22 | 15 |
| 2018/02 | 0 | 0 | 176 | 123 | 104 | 110 | 100 |
| 2018/03 | 0 | 0 | 121 | 87 | 77 | 76 | 47 |
| 2018/04 | 0 | 0 | 0 | 0 | 156 | 121 | 100 |
| 2018/05 | 0 | 0 | 0 | 0 | 0 | 123 | 56 |
| 2018/06 | 0 | 0 | 0 | 0 | 0 | 0 | 156 |
+---------+---------+---------+---------+---------+---------+---------+---------+
如何使用SQL成绩,非常感谢!