MySQL查询,返回子查询中每周的联系数量

时间:2018-02-01 16:08:34

标签: mysql subquery

我正在尝试提出一个查询,让我可以选择员工每周的联系人数量。

我想出了以下内容,但每天和每位员工都会返回0,0,0,0,0。

SELECT
@emp := A.id,
A.first_name,
(
   SELECT
    CONCAT_WS(',', mo, tu, we, th, fr)
   FROM
    (
        SELECT
            COALESCE(SUM(CASE WHEN WEEKDAY(B.contact_date) = 0 THEN 1 ELSE 0 END), 0) AS mo,
             COALESCE(SUM(CASE WHEN WEEKDAY(B.contact_date) = 1 THEN 1 ELSE 0 END), 0) AS tu,
             COALESCE(SUM(CASE WHEN WEEKDAY(B.contact_date) = 2 THEN 1 ELSE 0 END), 0) AS we,
             COALESCE(SUM(CASE WHEN WEEKDAY(B.contact_date) = 3 THEN 1 ELSE 0 END), 0) AS th,
             COALESCE(SUM(CASE WHEN WEEKDAY(B.contact_date) = 4 THEN 1 ELSE 0 END), 0) AS fr
        FROM
            `contacts` AS B
           WHERE
              B.user_id = @emp
           AND
              YEAR(B.contact_date) = 2018
           AND
              WEEK(B.contact_date) = 2
    ) q
) AS call_attempts
FROM
    `users` AS A
WHERE
    A.deactivated = 0
AND
    A.type = 1
ORDER BY
    A.first_name

小提琴:http://sqlfiddle.com/#!9/4f682c/7

0 个答案:

没有答案