mysql需要从查询中提取中值

时间:2017-07-05 16:41:58

标签: mysql median

我有以下查询,我需要从中提取total_views的中值。

    SELECT 
    @rownum:=@rownum + 1 AS row_num, total_views, projectId
FROM
    (SELECT 
        a.creation,
            a.projectId,
            devices,
            browserIds,
            devices + browserIds AS total_views
    FROM
        ((SELECT 
        projectId, creation
    FROM
        event
    WHERE
        kind = 'project_creation'
            AND creation > '2017-04-28') a
    INNER JOIN ((SELECT 
        COUNT(DISTINCT deviceId) AS devices, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'mobile'
    GROUP BY projectId) b
    JOIN (SELECT 
        COUNT(DISTINCT browserId) AS browserIds, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'web'
    GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
        OR a.projectId = c.projectId)
    ORDER BY total_views ASC) d,
    (SELECT @rownum:=0) e
;

这是结果的一部分:

1   1   151
2   1   256
3   1   301
4   2   404
5   2   305
6   3   895
7   4   654
8   4   369
9   9   874
10  10  123

我需要扩展查询以提取total_views的中值。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

找到解决方案,需要使用@rownum变量的值,而不是使用字段row_num的值来确定中间值的位置。 然后,我计算结果集中间的total_views的平均值。 (如果结果具有偶数行,则平均为两个中间值。如果结果集具有奇数行,则为中间值的平均值,与中间值相同)。 因此使用条件:

WHERE row_num in (CEIL(@rownum/2), FLOOR(@rownum/2))

完整查询:

SELECT avg(total_views) from 
(SELECT 
    @rownum:=@rownum + 1 AS row_num, total_views, projectId
FROM
    (SELECT 
        a.creation,
            a.projectId,
            devices,
            browserIds,
            devices + browserIds AS total_views
    FROM
        ((SELECT 
        projectId, creation
    FROM
        event
    WHERE
        kind = 'project_creation'
            AND creation > '2017-04-28') a
    INNER JOIN ((SELECT 
        COUNT(DISTINCT deviceId) AS devices, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'mobile'
    GROUP BY projectId) b
    JOIN (SELECT 
        COUNT(DISTINCT browserId) AS browserIds, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'web'
    GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
        OR a.projectId = c.projectId)
    ORDER BY total_views ASC) d,
    (SELECT @rownum:=0) e) f WHERE row_num in (CEIL(@rownum/2), FLOOR(@rownum/2))
;