简体   繁体   中英

How to count the number of occurrence of column values but without GROUP BY (not distinct values) mysql

id      title           numbers
1       chicken         1
2       meat            1
3       fish            1
4       fish            2
5       meat            2
6       fish            3
7       chicken         2
8       chicken         3

I want to construct the following output as above. Anyone can help me calculate number of occurrence of column values but without GROUP BY (not remove same values) , let create "numbers" field same as above , thank

Normal , if use COUNT(*) :

SELECT COUNT(*) FROM table GROUP BY title

But it remove same values :

id      title           numbers
1       chicken         3
2       meat            2
3       fish            3

i want to keep same values , and output like this :

id      title           numbers
1       chicken         1    
2       meat            1
3       fish            1
4       fish            2
5       meat            2
6       fish            3    
7       chicken         2     
8       chicken         3

I'm assuming your question is how to generate the numbers column in your sample output. If that's not correct, please clarify the question.

select  id
,       title
,       (
        select  count(*)
        from    Table1 t2
        where   t1.title = t2.title
                and t2.id <= t1.id
        ) as numbers
from    Table1 t1

Live example at SQL Fiddle.

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