0

data rows:

id status model  time
1  F      m0     12:00
2  S      m0     13:00
3  F      m0     14:00
4  S      m1     12:00
5  S      m1     13:00
6  S      m1     14:00

I want to get fail rate(status =f) group by model, result will be

model    fail_rate
m0       2/3
m1       0/3

Can we get the result using sql only?

Thanks in advance

2
  • Does the result have to look like 2/3 or 0.66 or 66.66%? Commented Oct 8, 2019 at 14:58
  • 0.66 is good one, 2/3 just for good understand Commented Oct 8, 2019 at 15:23

3 Answers 3

1

Easily, using aggregation:

select model,
       avg( (status = 'F')::int ) as fail_rate
from t
group by model;

Postgres can convert a boolean expression to a number, with "1" for true and "0" for false. The average of these values is the rate.

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

3 Comments

what does avg means? why not status = 'F' / all ?
@jamee . . . avg() is the aggregation function for "average". I have not idea what the rest of your comment means.
I undersand finally, avg is alternative method to get rate, that's very clever, S-Man clarify it
0

demo:db<>fiddle

SELECT
    model,
    SUM((status = 'F')::int) || '/' || COUNT(*) AS fail_rate
FROM
    mytable
GROUP BY model
  1. (status = 'F') gives true, if status == 'F'. Otherwise it gives false.
  2. Casting a type boolean (true/false) into an int yields in 1 for true, 0 for false
  3. Now you are able to sum up these integers. This gives you the sum of all 1 values, which is the count of all status == 'F'
  4. COUNT(*) gives all records
  5. With the string concatenation operator || you can create your expected result.

2 Comments

Your comments is very understandful
If you liked my answer, please do not forget to upvote. Upvoting is for all answers that are helpful although they might not be the one which solves the problem completely (what the accept is for). Thank you!
0

I did some research, get my version:

SELECT
    model,
    (COUNT(*) FILTER (WHERE status = 'F')::numeric / COUNT(*)) AS fail_rate
FROM
    mytable
GROUP BY model

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.