Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

mysql - Count the same id with group by in one single column

I have table kondisi like this

+------------+----------------+
| id_kondisi | id_sub_kondisi |
+------------+----------------+
| 01         | 0102           |
| 03         | 0302           |
| 01         | 0101           |
| 01         | 0102           |
| 01         | 0101           |
| 03         | 0301           |
| 03         | 0303           |
| 02         | 0202           |
| 01         | 0102           |
| 03         | 0301           |
| 01         | 0101           |
| 02         | 0203           |
| 03         | 0302           |
| 02         | 0202           |
| 02         | 0201           |
| 02         | 0202           |
+------------+----------------+
16 rows in set (0.00 sec)

I want to a result of the table that looks like this

+----------------+-------------+
| kondisi_tot    | coun_tot    |
+----------------+-------------+
| 01             |  6          |
| 0101           |  3          |
| 0102           |  3          |
| 02             |  5          |
| 0201           |  1          |
| 0202           |  3          |
| 0203           |  1          |
| 03             |  5          |
| 0301           |  2          |
| 0302           |  2          |
| 0303           |  1          |
+----------------+-------------+

SO i need to count the data id that have been looping. Just like the above result i know i have to use group by but how do i make the other column into one column ?

PS : My id_kondisi and id_sub_kondisi is a char type, not int type

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT ID, COUNT(*) FROM (
   SELECT id_kondisi as ID FROM kondisi
   UNION ALL
   SELECT id_sub_kondisi as ID FROM kondisi
) sub
GROUP BY ID
ORDER BY ID

Can have something to do with ordering cause having an ID as a number 02 will be less than 0102. Maybe you need to convert an ID to string in "order by" statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...