How to find median value with group by (MySQL)

前端 未结 1 1722
名媛妹妹
名媛妹妹 2021-01-16 04:05

Need to find median value of time difference between sent date and click date (in seconds) for each type of emails. I found solution just for all data:

SET @         


        
相关标签:
1条回答
  • 2021-01-16 04:54

    First, you need to enumerate the rows for each type. Using variables, this code looks like:

    select sc.*,
           (@rn := if(@t = id_type, @rn + 1,
                      if(@t := id_type, 1, 1)
                     )
           ) as seqnum
    from (select timestampdiff(second, s.date_sent, c.date_click) as time_diff,
                 s.id_type,
          from emails_sent s inner join
               emails_clicks c
               on s.id = c.id_email
          order by time_diff
         ) sc cross join
         (select @t := -1, @rn := 0) as params;
    

    Then, you need to bring in the total number for each type and do the calculation for the median:

    select sc.id_type, avg(time_diff)
    from (select sc.*,
                 (@rn := if(@t = id_type, @rn + 1,
                            if(@t := id_type, 1, 1)
                           )
                 ) as seqnum
          from (select timestampdiff(second, s.date_sent, c.date_click) as time_diff,
                       s.id_type,
                from emails_sent s inner join
                     emails_clicks c
                     on s.id = c.id_email
                order by time_diff
               ) sc cross join
               (select @t := -1, @rn := 0) as params
         ) sc join
         (select id_type, count(*) as cnt
          from emails_sent s inner join
               emails_clicks c
               on s.id = c.id_email
          group by id_type
         ) n
    where 2 * seqnum in (n.cnt, n.cnt, n.cnt + 1, n.cnt + 2)
    group by sc.id_type;
    
    0 讨论(0)
提交回复
热议问题