SUM多个Count和Group by

时间:2015-10-23 09:38:27

标签: mysql count sum

我需要按用户名和名称帐户

计算总操作ID(呼叫,会议和任务)组

我试试这个,但总数不正确

SELECT count(calls.id) + count(meetings.id) + count(tasks.id) AS 'total', users.user_name AS 'name', GROUP_CONCAT(accounts.name) AS 'accounts' 
FROM accounts, calls, users, meetings, tasks
WHERE accounts.id = calls.parent_id 
AND calls.assigned_user_id = users.id
AND accounts.id = meetings.parent_id
AND meetings.assigned_user_id = users.id
AND accounts.id = tasks.parent_id
AND tasks.assigned_user_id = users.id
GROUP BY name

2 个答案:

答案 0 :(得分:1)

如果没有使用代表性数据进行测试的好处,我的猜测是加入的5个表已经乘以行,因此总数不正确。在COUNT()中使用DISTINCT可能有所帮助,例如

SELECT
      COUNT(DISTINCT calls.id) 
    + COUNT(DISTINCT meetings.id) 
    + COUNT(DISTINCT tasks.id) AS 'total'
    , users.user_name AS 'name'
    , GROUP_CONCAT(DISTINCT accounts.name) AS 'accounts'
FROM accounts
      INNER JOIN calls ON accounts.id = calls.parent_id
      INNER JOIN users ON calls.assigned_user_id = users.id
      INNER JOIN meetings ON accounts.id = meetings.parent_id
                  AND meetings.assigned_user_id = users.id
      INNER JOIN tasks ON accounts.id = tasks.parent_id
                  AND tasks.assigned_user_id = users.id
GROUP BY
      users.user_name
;

注意我已经通过where子句交换旧的加入方式以获得更现代的方法,你真的应该加入。

另一种可能性是您的计数不正确,因为您正在使用INNER JOINS,它要求两个表中都存在数据才能返回行。所以也许你需要一些LEFT OUTER JOIN代替。

SELECT
      COUNT(DISTINCT calls.id) 
    + COUNT(DISTINCT meetings.id) 
    + COUNT(DISTINCT tasks.id) AS 'total'
    , users.user_name AS 'name'
    , GROUP_CONCAT(DISTINCT accounts.name) AS 'accounts'
FROM accounts
      LEFT OUTER JOIN calls ON accounts.id = calls.parent_id
      LEFT OUTER JOIN users ON calls.assigned_user_id = users.id
      LEFT OUTER JOIN meetings ON accounts.id = meetings.parent_id
                  AND meetings.assigned_user_id = users.id
      LEFT OUTER JOIN tasks ON accounts.id = tasks.parent_id
                  AND tasks.assigned_user_id = users.id
GROUP BY
      users.user_name
;

最终查询可能是连接的混合,一些是INNER,另一些是LEFT。

答案 1 :(得分:0)

`SELECT COUNT(calls.id) + COUNT(meetings.id) + COUNT(tasks.id) AS total, GROUP_CONCAT(users.user_name) AS name, GROUP_CONCAT(accounts.name) AS accounts
FROM accounts JOIN calls ON (accounts.id = calls.parent_id) 
JOIN users ON (calls.assigned_user_id = users.id) 
JOIN meetings ON (meetings.assigned_user_id = users.id) 
JOIN tasks ON (accounts.id = tasks.parent_id and tasks.assigned_user_id = users.id) 
GROUP BY users.user_name, accounts.name`