K
K
Kosk2018-11-07 16:40:59
PostgreSQL
Kosk, 2018-11-07 16:40:59

How to correctly implement a construct with a variable in Postgresql IF?

And so, there is a table of the form:
Table1

| id | column1 | column2 | 
| 1 | sss | sss| 
| 2 | sss | sss| 
| 3 | sss | sss| 
| 4 | sss | ses| 
| 5 | ses | ses| 
| 6 | ses | sew| 
| 7 | sew | seq|

Need to get:
| id | column1 | column2 | column3 |
| 1 | sss | sss| 1 |
| 2 | sss | sss| 1 |
| 3 | sss | sss| 1 |
| 4 | sss | ses| 2 |
| 5 | ses | ses| 2 |
| 6 | ses | sew| 3 |
| 7 | sew | seq| 4 |

I'm considering an option to increase the variable by 1 ...
select 1::int as I into temp table myvar; # создал переменную; воспользовался temp таблицей
select 
"id", 
"column1",
"column2", 
IF(("column2" <> "column1"), v.I++, v.I) AS "track" #как бы мог выглядеть синтаксис с инкрементацией, 
# переменную v.I  по условию увеличивать, то есть увеличить на 1, если условие верно.
from table1 , myvar v

In select'e approximate IF (...) syntax.
Could you tell me how to correctly implement the PostgreSQL IF ( condition, var++, var ) construct?
What is the alternative?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SharuPoNemnogu, 2018-11-07
@kosk

select id, 
           column1, 
           column2, 
           count(
                    case when column1 <> column2 
                    then 1 
                    else null end
           ) over(order by id) 
from table1;

A
Alexander Shelemetiev, 2018-11-07
@zoroda

There is a special window function for this case:

select id, 
           column1, 
           column2, 
           dense_rank() over(order by  column1,  column2)
from table1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question