如何显示给定人员的所有行的总和

时间:2014-11-14 16:20:16

标签: mysql sql sum

我正在尝试编写一个SQL查询来显示每个用户输入某些值的数量。

以下是我在MySQL中使用的表格。这些表不包含任何FK,仅用于性能目的的PK。

表LIST_DETAILS:

enter image description here

表用户:

enter image description here

表格配置:

enter image description here

下面是我尝试过的SQL查询。我遇到的问题是它只显示一个用户,而不是我期待的250个用户。

select job_name, concat(fname,' ',lname),  
       sum(disposition_category = 'Attempts') as Attempts,
       sum(disposition_category = 'RPC') as RPC,
       sum(disposition_category = 'Contacts') as Contacts,
       sum(disposition_category = 'Voted') as Voted,
       sum(disposition_category = 'RPC and Voted') as 'RPC and Voted',
       sum(disposition_category = 'Other') as Other,
       sum(disposition_category = 'Directory Assistance') as 'Directory Assistance'
from list_details ld
     join users u ON u.id = ld.id
     join dispositions d ON d.id = u.id
where security_level = 1;

这是我想看到的输出,但是当我需要看到250显示时,它只显示一个用户。

|       job_name         | concat(fname,' ',lname) | Attempts | RPC | Contacts | Voted | RPC and Voted | Other | Directory Assistance |
| SPDR-lower-range8-8-14 |      Rosybel Abreu      |    11    | 10  |    7     |   0   |      0        |   9   |         1           |

任何人都可以帮我纠正错误吗?

1 个答案:

答案 0 :(得分:3)

您遇到的问题是因为SUM()是一个聚合函数,它会对整个组进行求和。

您将整个员工组合成一行。您需要添加一个GROUP BY子句,以便MySQL知道要对哪些组求和的值。在这种情况下,我认为您希望按用户ID进行分组,请尝试以下操作:

SELECT job_name, CONCAT(fname,' ',lname) AS name,  
   SUM(disposition_category = 'Attempts') as Attempts,
   SUM(disposition_category = 'RPC') AS RPC,
   SUM(disposition_category = 'Contacts') AS Contacts,
   SUM(disposition_category = 'Voted') AS Voted,
   SUM(disposition_category = 'RPC and Voted') AS 'RPC and Voted',
   SUM(disposition_category = 'Other') AS Other,
   SUM(disposition_category = 'Directory Assistance') AS 'Directory Assistance'
FROM list_details ld
JOIN users u ON u.id = ld.id
JOIN dispositions d ON d.id = u.id
WHERE security_level = 1
GROUP BY u.id;