• 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

     

  • 相关阅读:
    java笔试面试题目收集(一)
    java--用 * 打印出各种图形(新手请进)
    TextView属性大赏
    Meterial Or Ios ?
    android开发之后端云bmob的使用
    关于android开发自定义view
    第二周作业——面向过程(或者叫结构化)分析方法与面向对象分析方法到底区别在哪里?
    移动APP开发使用什么样的原型设计工具比较合适?
    测试
    转:nohup命令及其输出文件
  • 原文地址:https://www.cnblogs.com/Mr-Cxy/p/5986675.html
Copyright © 2020-2023  润新知