Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequentially number rows by keyed group in SQL?

Tags:

sql

sequential

Is there a way in SQL to sequentially add a row number by key group?

Assume a table with arbitrary (CODE,NAME) tuples. Example table:

CODE NAME    
---- ----
A    Apple
A    Angel
A    Arizona
B    Bravo
C    Charlie
C    Cat
D    Dog
D    Doppler
D    Data
D    Down

Desired projection using CODE as the grouping attribute:

CODE C_NO NAME    
---- ---- ----
A    0    Apple
A    1    Angel
A    2    Arizona
B    0    Bravo
C    1    Charlie
C    0    Cat
D    0    Dog
D    1    Data
D    2    Down
D    3    Doppler

Thanks,

like image 432
Jé Queue Avatar asked Mar 28 '11 18:03

Jé Queue


People also ask

How do you set sequential numbers in SQL?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row. However, it can also be used to number records in different ways, such as by subsets.

How do I give a number to each row in SQL?

If you'd like to number each row in a result set, SQL provides the ROW_NUMBER() function. This function is used in a SELECT clause with other columns. After the ROW_NUMBER() clause, we call the OVER() function. If you pass in any arguments to OVER , the numbering of rows will not be sorted according to any column.

How do I add a sequence number to a SELECT query?

The Rank function can be used to generate a sequential number for each row or to give a rank based on specific criteria. The ranking function returns a ranking value for each row. However, based on criteria more than one row can get the same rank.

Can you group by count in SQL?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.


1 Answers

  • SQL Server
  • Oracle
  • Postgres
  • Sybase

MySQL doesn't AFAIK. This covers most bases..

SELECT
    CODE,
    ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO,
    NAME
FROM
    MyTable
like image 171
gbn Avatar answered Sep 23 '22 12:09

gbn