views:

44

answers:

2

I'd like to show the observation number for each record returned by a PostgreSQL query.

I think in 8.4 windowing functions can perform this capability.

Edit:
I think I just found the answer, but since this hasn't been asked before, I'll keep the question open. I also welcome non-windowing function possibilities.

Edit 2:
So a little thinking and I found out how to order without calling a function, which should be possible in any SQL-standard database that doesn't have a row_number function.

+4  A: 
select   row_number() over (order by <field> nulls last) as rownum, *
from     foo_tbl
order by <field>
vol7ron
+1  A: 

For versions prior to 8.4:

SELECT    count(*) rownum, foo.*
FROM      datatable foo
JOIN      datatable bar
          ON (foo.pk_id < bar.pk_id)
GROUP BY  foo.pk_id, foo.a, foo.b
ORDER BY  rownum
;

-- if there isn't a single unique/primary key field, you can concatenate fields
--    Example: ON (foo.a||foo.b||foo.c < bar.a||bar.b||bar.c)

Hope this helps someone.

vol7ron
This method should work on any SQL Standard compliant database
vol7ron
I think it's important to note that `null` values should concatentate to `null`. Thus, a `coalesce()` may need to be used.
vol7ron