简体   繁体   English

MySQL如何获取按语句分组的行数

[英]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 SELECT * FROM表GROUP BY Transid,下表中的其他ID

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 选择分组集合的min(id) ,然后使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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