1
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     
4

1 回答 1

4

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.

于 2013-01-16T12:05:15.050 回答