【问题标题】:Maximum date difference between rows for distinct users不同用户的行之间的最大日期差异
【发布时间】:2015-10-23 15:02:09
【问题描述】:

取一个简单的表格如:

User ID | Connection Date
1   | 12/10/2011
2   | 12/12/2011
1   | 12/14/2011
3   | 12/15/2011
1   | 12/16/2011
2   | 12/17/2011
2   | 12/18/2011
1   | 12/19/2011
3   | 12/20/2011
4   | 12/21/2011
2   | 12/21/2011

我想计算用户连接之间的最大日期差异。

谢谢

【问题讨论】:

  • “最大日期差”请详细说明?

标签: mysql date datediff


【解决方案1】:

几天...

select user_id, max(conn_date) - min(conn_date) from conn
group by user_id;

【讨论】:

    【解决方案2】:

    尝试如下

    select 
      mainqry.userid,
      max(mainqry.daysdiff) as max_date_diff
    From
    (
    select 
      qry.userid,
      -- qry.id1,
      -- qry.currid,
      ( Case when qry.id1 = qry.currid then qry.dt1 else null end ) prevconndt,
      qry.currdt,
      datediff((Case when qry.id1 = qry.currid then qry.dt1 else null end),qry.currdt) daysdiff
    from 
    (
    select 
      userid,
      @previd id1,
      @previd := userid as currid,
      @prevdt dt1,
      @prevdt := connectiondate as currdt
    from table1,(select @prevdt:=NULL,@previd := NULL) a  
    order by userid, connectiondate desc
    ) qry 
    ) MainQry
    group by MainQry.userid;
    

    它会在下面输出你给定的数据

    Userid max_date_diff
    1      4
    2      5 
    3      5 
    4      Null 
    

    您也可以使用下面的方法进行验证...

    select 
    qry.userid,
    -- qry.id1,
    -- qry.currid,
    ( Case when qry.id1 = qry.currid then qry.dt1 else null end ) prevconndt,
    qry.currdt,
    datediff((Case when qry.id1 = qry.currid then qry.dt1 else null end),qry.currdt) daysdiff
    from 
    (
    select 
      userid,
      @previd id1,
      @previd := userid as currid,
      @prevdt dt1,
      @prevdt := connectiondate as currdt
    from table1,(select @prevdt:=NULL,@previd := NULL) a  
    order by userid, connectiondate desc
    ) qry 
    

    【讨论】:

      猜你喜欢
      • 2013-01-28
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多