Sample Header Ad - 728x90

select row number increment on value change compared to previous return result

0 votes
2 answers
2419 views
I'm experimenting with Postgresql queries a bit and am trying to figure out if it's possible to write a query that would increment a row number counter when returned value changes. Example SOURCE (where SOURCE can be a sorted/unsorted sub-query/table): X|Y --- 0|0 0|1 0|0 1|0 1|0 1|1 2|0 Example increment on X: select X, Y, wishful_row_number(X) as Rn from SOURCE; 0,0,1 0,1,1 0,0,1 1,0,2 1,0,2 1,1,2 2,0,3 (row number changes every time X changes) Example increment on Y: select X, Y, wishful_row_number(Y) as Rn from SOURCE; 0,0,1 0,1,2 0,0,3 1,0,3 1,0,3 1,1,4 2,0,5 (row number changes every time Y changes - goes to a bigger number/different string even if that value was already seen before) So the Rn increment is not dependent on any "order by" or source sorting but just on the previously returned row. Can such a query be written (without store procedures and if possible without temporary tables)? EDIT: And yes, I know tables have no inherent ordering which is exactly the point of why I am trying to skip the "force me to order by" step and bind the Rn row generation on returned values (see my reply comment below). And yes, I understand that something like that might not be possible in SQL based on the "why would somebody in their right mind want to do that???" but as far as I'm concerned that's the SQL limitation and the answer is "no, it can't be done" even if some people have the fetish of down voting my question.
Asked by Domen Vrankar (111 rep)
Mar 10, 2024, 11:54 PM
Last activity: Mar 11, 2024, 10:46 AM