Mr_Cxy

导航

MySQL-计算7月重新激活客户第二种方法_20161022

 上周日休假去广西玩了一周,回来继续。

(一)上次用的是取当月首单日期,往前推30天 代码比较繁琐 这次方法是借助变量 错行进行判断 一个用户上次最后一次下单时间和下次下单时间的时间差

也就是形成一个相差天数的字段和第几天次的字段  去判断用户的留存激活新增属性

SQL代码如下

SELECT *, SUM(IF(上次金额 IS NULL,(@k := 1),(@k :=@k + 1))) AS 第几天次
FROM(
    SELECT b.*, c.订单日期  AS 上次订单日期,c.金额 AS 上次金额,TIMESTAMPDIFF(DAY,c.订单日期 ,b.订单日期) AS 相差天数
    FROM(
        SELECT a.*,(@i :=@i + 1) AS ID1
         FROM (
            SELECT city AS 城市,username AS 用户ID,order_date AS 订单日期,SUM(pay_money) AS 金额
            FROM `test_a03order`
            GROUP BY city,username,order_date
            ORDER BY city,username,order_date
        ) AS a,(SELECT @i := 0) AS a1
    ) AS b
    LEFT JOIN (
        SELECT a.*,(@j :=@j + 1) AS ID2
        FROM (
        SELECT city AS 城市,username AS 用户ID,order_date AS 订单日期,SUM(pay_money) AS 金额
        FROM `test_a03order`
        GROUP BY city,username,order_date
        ORDER BY city,username,order_date
        ) AS a,(SELECT @j := 1) AS a2
    )AS c  ON b.用户ID=c.用户ID AND ID1=ID2
) AS d
GROUP BY id1

 (二)上面的表当做一个子表 case when 进行条件判断 计算下7月份各城市用户ID的留存情况

SELECT  城市,用户ID,订单日期,
    CASE WHEN 第几天次=1 THEN "新增"
    WHEN 相差天数 IS NOT NULL AND 相差天数<=30 THEN "留存"
    WHEN 相差天数>30 THEN "重新激活" ELSE NULL END AS 激活情况
FROM (
    SELECT *, SUM(IF(上次金额 IS NULL,(@k := 1),(@k :=@k + 1))) AS 第几天次
    FROM(
        SELECT b.*, c.订单日期  AS 上次订单日期,c.金额 AS 上次金额,TIMESTAMPDIFF(DAY,c.订单日期 ,b.订单日期) AS 相差天数
        FROM(
        SELECT a.*,(@i :=@i + 1) AS ID1
         FROM (
            SELECT city AS 城市,username AS 用户ID,order_date AS 订单日期,SUM(pay_money) AS 金额
            FROM `test_a03order`
            GROUP BY city,username,order_date
            ORDER BY city,username,order_date
        ) AS a,(SELECT @i := 0) AS a1
        ) AS b
        LEFT JOIN (
        SELECT a.*,(@j :=@j + 1) AS ID2
        FROM (
            SELECT city AS 城市,username AS 用户ID,order_date AS 订单日期,SUM(pay_money) AS 金额
            FROM `test_a03order`
            GROUP BY city,username,order_date
            ORDER BY city,username,order_date
        ) AS a,(SELECT @j := 1) AS a2
        )AS c  ON b.用户ID=c.用户ID AND ID1=ID2
    ) AS d
    GROUP BY id1
) AS e
WHERE DATE_FORMAT(e.订单日期,"%Y%m")=201607

 

posted on 2016-10-22 08:48  Mr_Cxy  阅读(253)  评论(0编辑  收藏  举报