如何用groupby(mysql)查找中值

ux6nzvsh  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(381)

需要为每种类型的电子邮件找到发送日期和单击日期之间的时间差的中间值(以秒为单位)。我为所有数据找到了解决方案:

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));

是否可以添加group by id\u type语句?谢谢!

qyyhg6bp

qyyhg6bp1#

首先,需要枚举每种类型的行。使用变量,此代码如下所示:

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;

然后,您需要输入每种类型的总数并计算中位数:

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;

相关问题