1

我需要在 MySQL 中按天数 (ts_first) 计算用户会话长度 (ts_last-ts_first) 的中位数。尝试这样的事情,但它不起作用。

谢谢!

SET @row_number:=0;
SET @medin_group:=’’;

SELECT @row_number:=CASE 
WHEN @median_group= FROM_UNIXTIME(first_ts, '%t') THEN @row_number+1
ELSE 1
END AS count_by_time,
@median_group:= FROM_UNIXTIME(first_ts, '%t') AS median_group,
FROM_UNIXTIME(first_ts, '%t') AS by_time,
AVG(last_ts-first_ts) AS length,
(SELECT 
              COUNT (*)
         FROM 
                  User_sessions
           WHERE 
                      a.by_time=by_time) AS total_by_time
FROM 
   (SELECT   FROM_UNIXTIME(first_ts, '%t') AS by_time, AVG(last_ts-first_ts) AS length
FROM 
     User_sessions
  ORDERS BY by_time, length) AS 
4

1 回答 1

0

要获取表 User_sessions(id, first_ts, last_ts)的持续时间中值“last_ts - first_ts”:

Select MAX(totalSessions.duration) AS median
from
(
    SELECT User_sessions.last_ts - User_sessions.first_ts AS duration, @counter := @counter +1 AS counter
    FROM (select @counter:=0) initvar, User_sessions
    ORDER BY duration ASC
) totalSessions
where (50/100 * @counter) > counter

这通过以下方式起作用:

1)内部选择:为按时长排序的每一行User_sessions分配一个增量计数器,

lowest duration counter=1
2nd lowest counter=2
3rd lowest counter=3

2) 最后@counter = User_sessions 的总行数。

3) 一个外部选择,筛选具有counter < @counter 的行。

参考

于 2020-03-20T23:30:45.610 回答