0

I have two tables: users and works

I need write select query for count different names from users table where work_status = 1 from works table

enter image description here

The total is: 3 John, 1 Tom

I need get result:
John 2 (2 because one John work_status = 0 ant this not counting)
Tom 1

I have write select that can count different names, just need compared work_status..

SELECT name,COUNT(*) as num FROM users GROUP BY name

My query return:

enter image description here

5
  • 1
    This example Is totally wrong. Every user has only 1 work according to that relationship. Notice the user_id values in works table Commented Aug 14, 2014 at 9:00
  • @Hanky웃Panky You're right. I rewrote my answer. I think There are three differnt John working on the company. Commented Aug 14, 2014 at 9:10
  • This is just data example, me real table not this (but i need that query) Commented Aug 14, 2014 at 9:14
  • But your example isn't correct, our answer could be incorrect too. They are three different John, or all of them are the same person? Commented Aug 14, 2014 at 9:19
  • @JCalcines, The example data is clear, albeit poorly chosen. I believe you are getting hung up on concept. If you imagine the names as categories, say gender (John=Male, Tom=Female); the query can then be seen as get me the count of works with status 1 for each gender. Commented Aug 14, 2014 at 9:43

4 Answers 4

2

There is a problem in your question. So here you have two solutions.

If there are three different John working on the company, this is your query

SELECT u.name, COUNT(*) as num 
FROM users u INNER JOIN works w ON w.user_id = u.id 
WHERE w.work_status = 1
GROUP BY u.name, u.id

If there are only one John working in the company, your query is this one:

SELECT u.name, COUNT(*) as num 
FROM users u INNER JOIN works w ON w.user_id = u.id 
WHERE w.work_status = 1
GROUP BY u.name

Note: If three John are the same person, you should delete the 2 last and on the works table change user_id = 3 and user_id = 4 for user_id = 1

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

Comments

1

This is a simple JOIN query:

  SELECT u.name, COUNT(*) num
    FROM users u
    JOIN works w
      ON w.user_id = u.id
     AND w.work_status = 1
GROUP BY u.name

Comments

1

This one should do the job:

SELECT users.name,SUM(works.work_status) as num 
  FROM users,works 
  WHERE users.id=works.id 
  GROUP BY name

Comments

1
SELECT 
  users.`name`,
  COUNT(*) num 
FROM
  users,
  works 
WHERE users.`id` = works.`user_id` 
  AND works.`work_status` = 1 
GROUP BY users.`name` ;

Comments

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.