日期比较搞。。。

总结:

凡是统计第n天内的问题,要求包含当天,利用DATE_SUB前推日期时要用【T- (n-1)】

例子:

要求统计近7天内,区间为【当天前推6天,当天】

要求统计近14天内,区间为【当天前推13天,当天】

要求统计近30天内,区间为【当天前推29天,当天】

...

代码如下:


WITH today AS(
SELECT MAX(DATE(in_time)) FROM tb_user_log #今天的日期
)

SELECT 
  user_grade,
  ROUND(COUNT(uid) / (SELECT COUNT(DISTINCT uid) FROM tb_user_log), 2) ratio
FROM (
  SELECT 
    uid,
    CASE 
      WHEN MAX(DATE(in_time)) BETWEEN DATE_SUB((SELECT * FROM today), INTERVAL 6 DAY)
                              AND
                              (SELECT * FROM today) #最后活跃在近七天(T-6)
           AND
           MIN(DATE(in_time)) < DATE_SUB((SELECT * FROM today), INTERVAL 6 DAY) #非新晋用户:注册日期在近七天前
           THEN '忠实用户'
      WHEN MIN(DATE(in_time)) BETWEEN DATE_SUB((SELECT * FROM today), INTERVAL 6 DAY) 
                                      AND #新晋用户:首次登陆日期在近七天(T-6)之内
                                      (SELECT * FROM today) THEN '新晋用户'
      WHEN MAX(DATE(in_time)) BETWEEN DATE_SUB((SELECT * FROM today), INTERVAL 29 DAY) 
                              AND #沉睡用户:最后活跃时间在7天之前(T-7),30天之内(T-29)
                              DATE_SUB((SELECT * FROM today), INTERVAL 7 DAY) THEN '沉睡用户'
      ELSE '流失用户'
    END user_grade
  FROM tb_user_log
  GROUP BY 1
) t
GROUP BY 1
ORDER BY 2 DESC