How to enumerate returned rows in SQL?

SilentGhost picture SilentGhost · Jun 15, 2010 · Viewed 29.3k times · Source

I was wondering if it would be possible to enumerate returned rows. Not according to any column content but just yielding a sequential integer index. E.g.

select ?, count(*) as usercount from users group by age

would return something along the lines:

1    12
2    78
3     4
4    42

it is for https://data.stackexchange.com/

Answer

KM. picture KM. · Jun 15, 2010

try:

SELECT
    ROW_NUMBER() OVER(ORDER BY age) AS RowNumber
        ,count(*) as usercount 
    from users 
    group by age