2014-11-14 51 views
0

我正在尝试编写一个SQL查询来显示每个用户的某些值的输入量。如何显示给定人的所有行的总和

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

表LIST_DETAILS:

enter image description here

表USERS:

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   | 

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

+0

我正确地认为'11'尝试是针对所有员工的,而不仅仅是上面显示的那个? – AdamMc331 2014-11-14 16:40:19

回答

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; 
+0

我认为它也应该由job_name分组,但基本上这是正确的。 – evanv 2014-11-14 16:44:26

+0

我觉得很愚蠢。但它只拉了45行,我应该有243左右。那么这是否意味着它可能是我的联合声明? – AznDevil92 2014-11-14 16:47:15

+1

它可能是。一个好的测试是从连接中选择所有的东西,然后看看有多少行以这种方式返回。你确定你有243个实际用户?或者是否有45个用户跨越这243行? – AdamMc331 2014-11-14 16:50:31

相关问题