How to find median value with group by (MySQL)

梦想的初衷 提交于 2019-12-01 12:02:11

问题


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 @rowindex := -1;
SELECT g.type, g.time_diff
FROM
(SELECT @rowindex:=@rowindex + 1 AS rowindex,
TIMESTAMPDIFF(SECOND, emails_sent.date_sent, emails_clicks.date_click) AS time_diff,
emails_sent.id_type AS type
FROM emails_sent inner join emails_clicks on emails_sent.id = emails_clicks.id_email
ORDER BY time_diff) AS g
WHERE g.rowindex IN (FLOOR(@rowindex / 2) , CEIL(@rowindex / 2));

Is it possible to add group by id_type statement? Thanks!


回答1:


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;


来源:https://stackoverflow.com/questions/53802183/how-to-find-median-value-with-group-by-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!