1

I have a query SELECT * from TABLE which gives the result as below table:

enter image description here

Expected column is as below:

enter image description here

I want to frame a new column like whenever we get the value as 0 then the number should be incremented by 1. I tried DENSE_RANK() , ROW_NUMBER() but couldn't get the exact result which mentioned. Is that possible in PostgreSQL.

Akhilesh Mishra
  • 5,876
  • 3
  • 16
  • 32

1 Answers1

1

Try This:

select name, value,
sum(case when value=0 then 1 else 0 end) over (order by  "sno") 
from (
select row_number() over() as "sno",* from example
     ) tab

DEMO

NOTE: Please note that there is no guaranteed that you will get same output always due no ordering field in your raw data.

So Better approach is to add some field in your view output by which it can be ordered and run the query like below:(assuming you have a ID field)

select 
  name, 
  value, 
  sum(case when value=0 then 1 else 0 end) over (order by id) 
from example

DEMO

Akhilesh Mishra
  • 5,876
  • 3
  • 16
  • 32