2012-06-27 83 views
1

這是複雜的查詢,我希望能夠實現它一個語句,而不是必須在PHP中處理數組值。MySQL加入加數加加總和

爲了達到期望的輸出:

User Jobs Total 
John D. 5  $1245.67 
Mary L. 3  $800.56 

到目前爲止,這是查詢我:

SELECT 
    SUM(job.cost) AS sum, 
    COUNT(DISTINCT job.user) as count, 
    user.id, user.firstname, user.lastname 
FROM  `job` 
LEFT JOIN `user` ON job.user = user.id 
GROUP BY user.id 

但計數值是錯誤的:它是不同的用戶,所以當然每個人都會出錯。我該如何解決?

user

id, name, etc. 

job

id, user, cost 

一個user許多job


UPDATE

這似乎是工作的權利:

SELECT 
    SUM(job.cost) AS sum, 
    COUNT(1) as count, 
    user.id, user.firstname, user.lastname 
FROM `job` 
LEFT JOIN `user` ON job.user = user.id 
GROUP BY user.id 
+0

請介紹一些樣本數據表結構。 –

+1

或http://sqlfiddle.com/#!2 – biziclop

+1

'COUNT(DISTINCT job.id)'(或'job'中的任何其他唯一列) – Wrikken

回答

2
SET @seq = 0; 

SELECT place FROM 

(SELECT 
    @seq := @seq + 1 AS place 
    SUM(job.cost) AS sum, 
    COUNT(1) as count, 
    user.id, user.firstname, user.lastname 
FROM  `job` 
LEFT JOIN `user` ON job.user = user.id 
GROUP BY user.id 
ORDER BY COUNT(1) DESC) 

AS list 
WHERE list.id = 'my_user_id' 
+0

我將如何確定一個特定用戶在結果中的位置,而不必循環它們?任何想法? ---- 其實,我只需要知道他們在總工作數方面的位置 – AVProgrammer

+0

按何種順序安置? – vearutop

+0

降序,大多數工作至少 – AVProgrammer