MySQL. How can I COUNT() but insert different value on the different column?

table users

|   id   |   username   |   status   |   
|   1    |   cahya      |   steady   |
|   2    |   kadek      |   steady   |
|   3    |   cahya      |   steady   |
|   4    |   erno       |   ready    |
|   5    |   kadek      |   go       |

hopping result is like below

| username | steady | ready | go |
|  cahya   |   2    |   0   | 0  |
|  kadek   |   1    |   0   | 1  |
|  erno    |   0    |   1   | 0  |

I did it separated but I think it is not a good work

select username, count(status) from users where status = 'steady'
select username, count(status) from users where status = 'ready'
select username, count(status) from users where status = 'go'

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

SELECT username, 
       SUM(status = 'steady') AS steady, 
       SUM(status = 'ready') AS ready, 
       SUM(status = 'go') AS go
FROM users 
GROUP BY 1;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x