2

I have this table in a mysql database :

TABLE rating
| id         (int, primary)
| id_company (int, index)
| state      (enum: 'waiting','done','refuse')
| rating     (int between 1 and 5)

I want to get this stats for one id_company :

  • number lines
  • number lines with state=done
  • sum rating
  • sum rating with state=done

For this i have 2 queries (exemple with id_company=2) :

SELECT COUNT(1) as `nbr`, SUM(`rating`) as `total` FROM `rating` WHERE `id_company`=2
SELECT COUNT(1) as `nbr`, SUM(`rating`) as `total` FROM `rating` WHERE `id_company`=2 AND `state`='done'

But it is possible to make an unique query to get this stats ?

1 Answer 1

1

You can try something like this:

SELECT COUNT(*) as `nbr1`, 
       SUM(`rating`) as `total1`,
       SUM(`state`='done') as `nbr2`, 
       SUM(CASE 
              WHEN `state`='done' THEN `rating` 
              ELSE 0 
           END) as `total2`  
FROM `rating` 
WHERE `id_company`=2 
Sign up to request clarification or add additional context in comments.

6 Comments

Well done, thanks. Why not let id_company in the where clause ? it works too.
@Jeremy Yes you are right. The id_company predicate should also be used in the WHERE clause because it makes the query run faster.
why you save 'id_company=2` in cases while adding where ?
@spash58 i remove it in my query, it's indeed not necessary
@splash58 OK, I've edit my query to make it cleaner.
|

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.