1

This is complex query, and I was hoping to achieve it one statement, rather than have to juggle array values in PHP.

To achieve the desired output of:

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

So far, this is the query I have:

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

But the count value is wrong: it's the distinct user, so of course each is going to be wrong. How do I fix this?

TABLE user

id, name, etc.

TABLE job

id, user, cost

With ONE user TO MANY job


UPDATE

This seems to be working right:

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
6
  • Please describe your table structure with some sample data. Commented Jun 27, 2012 at 21:47
  • 1
    Or an sqlfiddle.com/#!2 Commented Jun 27, 2012 at 21:48
  • 1
    COUNT(DISTINCT job.id) (or any other unique column in job Commented Jun 27, 2012 at 21:48
  • @Wrikken Actually, COUNT(job.user) did it, posting correct (as far as I know) query. Commented Jun 27, 2012 at 21:51
  • SQLFiddle has been around for a looong time :P Commented Jun 27, 2012 at 21:57

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

How would I determine a specific user's placement in the results without having to loop through them? Any ideas? ---- Actually, I just need to know their placement in regards to number of total jobs
Descending order, most jobs to least

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.