2

How can I construct a query to show an auto-incremented number?

I have a query, select * from data, which results in:

Name    State  
a       malaysia  
b       Indonesia  

I want this:

No      Name    State  
1       a       malaysia  
2       b       Indonesia  

How might I do this?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
rian
  • 57
  • 4

3 Answers3

3
SELECT Name
, State
, RANK() OVER (ORDER BY Name, State) as Ranking
FROM Data
Vinnie
  • 3,889
  • 1
  • 26
  • 29
0

I don't know if there's a database-agnostic way.

Oracle allows you to state the rownum (http://www.adp-gmbh.ch/ora/sql/rownum.html) as a column to return.

H2 supports this syntax as well

The answer might depend on the flavor of database you are using.

EdH
  • 4,918
  • 4
  • 24
  • 34
0

Since you don't say in what database lets just make it PostgreSQL:

select 0+row_number() OVER(ORDER BY name DESC) as position, * from test.users ORDER BY name

This might be different in other databases (it will for sure). The idea should be the same thought, so this way you know how to do in one. Should be easy to do it in some other.

RGPT
  • 564
  • 1
  • 7
  • 16