0

I'm trying to count all records from my 'jobs' table that have a 'completed' status, excluding any jobs that are either 'fix-it' or 'vacancy' job types. This is what I'm using, but I'm not sure if this is giving me the correct results:

SELECT id, client_id, COUNT(*) AS count FROM jobs 
WHERE jobType != 'fix-it' AND jobType != 'vacancy' AND status = 'completed' 
GROUP by jobs.client_id

I then look at the result to see if I have two or more completed jobs under a given client.

Does this look correct?

4
  • Could you post a little example data? Your code looks OK, just wanted to test stuff. Commented Sep 10, 2012 at 20:26
  • If "jobType" is NULL, do you want to see those records? Why do you select "id" in the query? What do you think it is telling you? Commented Sep 10, 2012 at 20:53
  • Yes, i would want to see those records. Wouldn't they be included though, because I'm using != to filter? NULL would not equal either 'vacancy' or 'fix-it', and as such it would be included right? As far as the 'id' goes, you're right, I don't need it. Commented Sep 10, 2012 at 20:59
  • Re: NULL, no. NULL != col evaluates to NULL, not true or false. Re: "id", it's not just not needed, it doesn't make sense, and I'd recommend using ONLY_FULL_GROUP_BY. Commented Sep 10, 2012 at 21:12

2 Answers 2

2

You could replace the two jobtype things with a single NOT IN clause, to make things a little more legible...

WHERE jobType NOT IN ('fix-it', 'vacancy') AND ...

otherwise it looks ok

Sign up to request clarification or add additional context in comments.

Comments

0

This works in SQL Server, not sure about MySql:

SELECT id, client_id, COUNT(*) AS count FROM jobs 
WHERE jobType != 'fix-it' AND jobType != 'vacancy' AND status = 'completed' 
GROUP by jobs.client_id
HAVING Count(*) > 1

5 Comments

it won't work. you'll get the "selecting non-aggregate fields not in a group by" error. SQL server's stupid like that.
I actually do that > 1 count check using PHP, so that's not a problem. I'm mainly concerned whether the above query would generate the intended results, given that I'm pretty new to using COUNT.
@Marc B's comment is very true, you'd have to add the id and client id to group by in SQL server
@Jeremy Unless you want to display all the results, I always try to filter in the query...
@MarcB You have it backwards. It's MySQL that is stupid here, by returning an indeterminate id.

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.