简体   繁体   中英

Mysql how to get the count of rows grouped in a group by statement

I'm trying to get the count of the number of rows being grouped together in each of the result rows. For example:

SELECT * FROM table GROUP BY transid, other id on the following table

id      transid  other id
------------------------------
|1      |1        |1        |
|2      |1        |1        |
|3      |1        |1        |
|4      |1        |2        |
|5      |1        |2        |
|6      |1        |2        |
|7      |2        |1        |
|8      |2        |1        |
|9      |2        |2        |
|10     |3        |1        |
|11     |3        |1        |

RESULT:

 id      transid  other id
------------------------------
|1      |1        |1        |
|4      |1        |2        |
|7      |2        |1        |
|10     |2        |2        |
|11     |3        |1        |

How can I get:

 id      transid  other id   count
-------------------------------------
|1      |1        |1     |  3
|4      |1        |2     |  3
|7      |2        |1     |  2
|9      |2        |2     |  1
|10     |3        |1     |  2

Thank you.

Pick the min(id) of the grouped set and use count () to get the set count

Select min(id), transid, [other id], count(*) count
from table
Group by transid, [other id]

If all you're trying to do is count how many times there is a duplicate, you can simply do

Select Count(*), col1, col2 from tbl
group by col1, col2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM