2014-11-14 52 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

相關問題