Вы можете использовать что-то вроде этого ( без вычисления медианы ):
SELECT MIN(diff) AS `MIN`, MAX(diff) AS `MAX`, SUM(diff) / COUNT(DISTINCT user_id) AS `AVG`
FROM (
SELECT ID, user_id, DATEDIFF((SELECT t2.createdAt FROM test t2 WHERE t2.user_id = t1.user_id AND t1.createdAt <= t2.createdAt AND t2.id <> t1.id LIMIT 1), t1.createdAt) AS diff
FROM test t1
WHERE order_status_id in (4, 5, 6, 8)
) DiffTable
WHERE diff IS NOT NULL
Медиана гораздо сложнее вычислить на MySQL. Но вы можете использовать что-то вроде этого на основе этого ответа на StackOverflow . Как видите, запрос становится очень грязным. Нет такой функции, как SUM
или AVG
на MySQL для получения медианы.
SELECT MIN(DiffTable.diff) AS `MIN`, MAX(DiffTable.diff) AS `MAX`, SUM(DiffTable.diff) / COUNT(DISTINCT user_id) AS `AVG`, MIN(median.diff) AS `MEDIAN`
FROM (
SELECT ID, user_id, DATEDIFF((SELECT t2.createdAt FROM test t2 WHERE t2.user_id = t1.user_id AND t1.createdAt <= t2.createdAt AND t2.id <> t1.id LIMIT 1), t1.createdAt) AS diff
FROM test t1
WHERE order_status_id in (4, 5, 6, 8)
) DiffTable, (
SELECT m1.diff FROM (
SELECT ID, user_id, DATEDIFF((SELECT t2.createdAt FROM test t2 WHERE t2.user_id = t1.user_id AND t1.createdAt <= t2.createdAt AND t2.id <> t1.id LIMIT 1), t1.createdAt) AS diff
FROM test t1
WHERE order_status_id in (4, 5, 6, 8)
) m1, (
SELECT ID, user_id, DATEDIFF((SELECT t2.createdAt FROM test t2 WHERE t2.user_id = t1.user_id AND t1.createdAt <= t2.createdAt AND t2.id <> t1.id LIMIT 1), t1.createdAt) AS diff
FROM test t1
WHERE order_status_id in (4, 5, 6, 8)
) m2
WHERE m1.diff IS NOT NULL AND m2.diff IS NOT NULL
GROUP BY m1.diff
HAVING SUM(SIGN(1-SIGN(m1.diff-m2.diff))) = (COUNT(*)+1)/2
) median
WHERE DiffTable.diff IS NOT NULL
демо на dbfiddle.uk