mysql count(*)with group by by by one,而不是总和

时间:2016-07-08 10:53:22

标签: mysql count group-by

主要思想是:

id  name  count_n
1   'a'   3
2   'a'   3
3   'a'   3
4   'b'   2
5   'b'   2

我希望得到count_n这样:

id  name  count_n
1   'a'   1
2   'a'   2
3   'a'   3
4   'b'   1
5   'b'   2

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用变量:

SELECT id, name,
       @seq := IF(@n = name, @seq+1,
                  IF(@n := name, 1, 1)) AS count_n
FROM mytable
CROSS JOIN (SELECT @seq := 0, @n := '') AS v
ORDER BY id

Demo here