I have a table with two fields.
The 1st is a ‘key’ and the 2nd field can have only value ‘A’ or ‘B’.
I would like, with a SELECT, to retrieve a recordset that, grouping by the 1st field, have two columns with the count of the values of the 2nd field.
Table:
Key | Value |
---|---|
1 | A |
1 | B |
2 | A |
3 | B |
Result:
Key | Counf of A | Counf of B |
---|---|---|
1 | 1 | 1 |
2 | 1 | 0 |
3 | 0 | 1 |
2
Answers
If you use MySQL (as it’s taged in your question), you don’t need
CASE
.The query will simply be:
If your RDBMS does not support above query, I would prefer
COUNT
here overSUM
.COUNT
returns zero if onlyNULL
appears.Therefore the
CASE
doesn’t require anELSE
clause, so it’s more readable.See this sample fiddle