这是一个复杂的查询,我希望能够实现一个语句,而不是在PHP中处理数组值。
达到所需的输出:
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
更新
这似乎正常:
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 :(得分: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'