views:

73

answers:

5

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 http://odata.stackexchange.com/

+2  A: 

try:

SELECT
    ROW_NUMBER() OVER(ORDER BY age) AS RowNumber
        ,count(*) as usercount 
    from users 
    group by age
KM
Thanks, KM. you've very helpful
SilentGhost
+1  A: 

How you'd do that depends on your database server. In SQL Server, you could use row_number():

select  row_number() over (order by age)
,       age
,       count(*) as usercount 
from    users 
group by 
        age
order by
        age

But it's often easier and faster to use client side row numbers.

Andomar
the `partition by age` will cause the number to rest for each `age`, and the query is grouping by age, so your row number will be 1 for every row.
KM
@KM: Right, edited in answer
Andomar
+1  A: 

use rownumber function available in sql server

SELECT 
    ROW_NUMBER() OVER (ORDER BY columnNAME) AS 'RowNumber',count(*) as usercount
    FROM users
Pranay Rana
thanks for the link
SilentGhost
+1  A: 

For MySql:

SELECT  @row := @row + 1 as row FROM anytable a, (SELECT @row := 0) r
BenV
+1  A: 

If it's Oracle, use rownum.

SELECT SOMETABLE.*, ROWNUM RN
FROM SOMETABLE
WHERE SOMETABLE.SOMECOLUMN = :SOMEVALUE
ORDER BY SOMETABLE.SOMEOTHERCOLUMN;

The final answer will entirely depend on what database you're using.

FrustratedWithFormsDesigner