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

时间:2015-03-04 21:04:11

标签: mysql sql

我试图计算每个结果行中组合在一起的行数。例如:

SELECT * FROM table 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        |

结果:

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

我怎样才能得到:

 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

谢谢。

2 个答案:

答案 0 :(得分:1)

选择分组的min(id)并使用count()获取设置数

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

答案 1 :(得分:0)

如果您要做的只是计算重复次数,您可以直接执行

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