zoukankan      html  css  js  c++  java
  • sql

    计算用户距上次访问的天数,根据imei号区分不同的用户,如果时间段内只有一次访问则为0。 

    初始化数据 
    CREATE TABLE `pd` ( 
      `imei` varchar(32) NOT NULL DEFAULT '', 
      `dat` datetime DEFAULT NULL 
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

    -- ---------------------------- 
    -- Records of pd 
    -- ---------------------------- 
    INSERT INTO `pd` VALUES ('1', '2013-07-25 00:00:01'); 
    INSERT INTO `pd` VALUES ('1', '2013-07-26 00:00:02'); 
    INSERT INTO `pd` VALUES ('2', '2013-07-23 00:00:04'); 
    INSERT INTO `pd` VALUES ('2', '2013-07-26 00:00:03'); 
    INSERT INTO `pd` VALUES ('3', '2013-07-26 00:00:01'); 


    脚本 
    select * from ( 
        select imei user_id, max(max_dd) , max(max_dd_2), to_days( max(max_dd)) - to_days(max(max_dd_2)) days  from ( 
            select imei, max_dd, max_dd_2 from ( 
                  select tmp.imei, tmp.dates, 
                               if(@imei=tmp.imei, @rank:=@rank+1,@rank:=1) as rank, 
                          if(@rank = 1, @max_d := tmp.dates, @max_d := null) as max_dd, 
                          if(@rank = 2, @max_d_2 := tmp.dates, @max_d_2 := null) as max_dd_2, 
                                @imei:=tmp.imei 
                  from (select imei, dates from pb order by imei asc ,dates desc ) tmp , 
                    (select @rownum :=0 , @imei := null ,@rank:=0, @max_d :=null, @max_d_2 := null) a 
          ) result 
        ) t 
        group by imei 
        having count(*) > 1 
    ) x where x.days >= 1 and EXISTS (select 'x' from pb where dates > '2013-07-26 00:00:00') 

    如果表数据量大,千万不要用union all等操作 

  • 相关阅读:
    第二章作业第2题--苏志华
    小学生四则运算应用软件(一)
    YOLO1至YOLOV3方法讲解
    C++ STL中的二分查找
    C++ 中的prioriy_queue 优先级队列 转
    C++ 中的容器(栈、堆、队列) 转
    从尾到头打印链表
    替换空格
    C++中vector<vector<int> >
    对称平方数
  • 原文地址:https://www.cnblogs.com/ctaixw/p/5484359.html
Copyright © 2011-2022 走看看