如何按组计算行数并将其添加到子查询中?

时间:2016-01-07 14:31:55

标签: mysql sql

我需要计算以小时为单位的行数,然后将其添加到选择子查询中,但我在此行中遇到错误AND DATE(created_at) = T.day_start AND user_id = T.user_id

这是我的问题:

SELECT
    COUNT(*)
FROM
    (
        SELECT
            HOUR (call_start_at) AS hours,
            count(*) AS calls
        FROM
            calls
        WHERE
            1
        AND user_id = 8
        AND call_start_at >= '2016-01-06 00:00:00'
        AND call_start_at <= '2016-01-06 23:59:59'
        GROUP BY
            HOUR (call_start_at)
    ) AS T1

我尝试这个添加来选择子查询,但是当我改变时,在T.day_start和T.user_id的标记行上出错了。

这是我的测试:

SELECT
    T2.name,
    T2.calls,
    ROUND(calling_time * 100 / working_time, 2) AS percent,
    T2.calling_time,
    T2.working_time
FROM
    (SELECT
        T.name,
        (SELECT COUNT(*) FROM calls AS C WHERE DATE(C.created_at) = T.day_start AND C.user_id = T.user_id) AS calls,
        (SELECT
            COUNT(*)
        FROM 
        (SELECT
            HOUR(call_start_at) as hours,
            count(*) as calls
        FROM 
            calls
        WHERE 1
            AND DATE(created_at) = T.day_start AND user_id = T.user_id // marked line
        GROUP BY
            HOUR(call_start_at)) as T3
        ) as row_count,
        (SELECT SUM(call_length) FROM calls AS C WHERE DATE(C.created_at) = T.day_start AND C.user_id = T.user_id) AS calling_time,
        SUM(T.working_time) AS working_time
    FROM
        (SELECT
            U.username AS name,
            U.id AS user_id,
            DATE(UW.start) as day_start,
            UW.length AS working_time
        FROM
            users AS U
            LEFT JOIN users_worktime AS UW ON UW.user_id = U.id
        WHERE 1
            AND U.type = 'agent'
            AND UW.start >= '2016-01-06 00:00:00'
            AND UW.start <= '2016-01-06 23:59:59'
        ) AS T
    GROUP BY
        T.name, T.user_id, T.day_start
    ) AS T2

1 个答案:

答案 0 :(得分:2)

您可以更简单地将查询编写为:

    SELECT COUNT(DISTINCT HOUR(call_start_at)) as num
    FROM  calls
    WHERE 1 AND
          user_id = 8 AND
          call_start_at >= '2016-01-06 00:00:00' AND
          call_start_at <= '2016-01-06 23:59:59'

这将允许您使用关联子句。

注意:这会忽略NULL个值。我认为这不是问题(如果是这样就很容易修复)。