除了ID列之外,如何合并和计算相同的MySQL行?

时间:2011-09-03 11:46:10

标签: mysql count

我希望能够合并行,并找出除ID之外的相同数量。例如,如果我要使用此表:

+---------+-----------+-----------+
|  ID     |  Col 1    |  Col 2    |
+---------+-----------+ ----------+
|  1      |  1        |  5        |
|  2      |  1        |  5        |
|  3      |  4        |  9        |
|  4      |  3        |  9        |
|  5      |  1        |  5        |
|  6      |  1        |  5        |
|  7      |  1        |  5        |
|  8      |  4        |  9        |
+---------+-----------+-----------+

它会变成:

+---------+-----------+-----------+---------+
|  ID     |  Col 1    |  Col 2    |  Count  |
+---------+-----------+ ----------+---------+
|  1      |  1        |  5        | 5       |
|  2      |  4        |  9        | 2       |
|  3      |  3        |  9        | 1       |
+---------+-----------+-----------+---------+

对此的查询是什么?

2 个答案:

答案 0 :(得分:2)

在结果中的ID列旁边,对我来说看起来像你需要:

SELECT Col1, Col2, Count(Col1)
FROM myTable
GROUP BY Col1, Col2

答案 1 :(得分:2)

select col1,col2,count(*) as `count`
from table
group by col1,col2