4

I have a table like this:

 num | type
-----+------
 123 | 3
 123 | 2
 123 | 3
 123 | 2
 124 | 3
 124 | 1
 124 | 3
 124 | 3

I want to group by the num column, and have a column counting each distinct type (I know all the possible values here in advance). So I would get:

 num | 1 | 2 | 3
-----+---+---+---
 123 | 0 | 2 | 2
 124 | 1 | 0 | 3

Is this possible with SQL? I am using MySql.

1 Answer 1

7
SELECT `num`,
    SUM(type = 1) as `1`, 
    SUM(type = 2) as `2`, 
    SUM(type = 3) as `3`
FROM `your_table`
GROUP BY `num`
Sign up to request clarification or add additional context in comments.

3 Comments

That's certainly more concise than sum(case when type = 1 then 1 end) ! +1
@Andomar - It certainly is. Although I can't express a strong/clear reason, I actually don't like using that type of behaviour. I'd up-vote SUM(IF(type=1, 1, 0)) though. Does anyone else have an opinion on whether SUM(type=1) is better or worse than SUM(IF(type =1, 1, 0))?
@Dems: I like the short version better. But it is good to have an alternative mentioned in your comment.

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.