0

I have a table that looks like:

field1 | field2
   1   | ready
   2   | ready
   1   | in_progress
   1   | ready
   2   | in_progress

How can i count number of "ready" fields for each field1? For this example answer must be:

field1 | field2
   1   |   2
   2   |   1
1

2 Answers 2

1

Simple filter and aggregation will do:

SELECT field1,
    COUNT(*) AS field2
FROM your_table
WHERE field2 = 'ready'
GROUP BY field1;

If you want to get those field1 values where count can be 0:

SELECT field1,
    SUM(field2 = 'ready') as field2
FROM your_table
GROUP BY field1;

SUM(field2 = 'ready') uses the fact that MySQL treats true as 1 and false as 0.

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

3 Comments

It's pretty basic SQL. Not much to explain I'm afraid :)
Well, i 've try to add your code to my query. It doesn't work still, cause i have a bit more sophisticated schema. Should i ask new question or edit this one?
@КириллТимофеев Please ask a new question.
0

This can be done using simple aggregation using the count() function:

select field1, count(field2) as field2
from yourtable
where field2 = 'ready'
group by field1

By filtering your data using a WHERE = 'ready' you then count the number of rows for each value in field1.

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.