简体   繁体   中英

mysql count(*) with group by get one by one , not the total sum

The main idea is this:

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

I want to get the count_n like this:

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

How can I do this?

You can use variables for this:

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

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