這是複雜的查詢,我希望能夠實現它一個語句,而不是必須在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
請介紹一些樣本數據表結構。 –
或http://sqlfiddle.com/#!2 – biziclop
'COUNT(DISTINCT job.id)'(或'job'中的任何其他唯一列) – Wrikken