Skip to content
Advertisement

In SQL I Want Result Like

Select * from CompanyName

Field1
A
A
A
B
B
C
D
E
E
E
E

This Is My Output I Want To Add 1 In Last Same Filed Like

Field1 Filed2
A       0
A       0
A       1
B       0
B       1
C       1
D       1
E       0
E       0
E       0
E       1

Advertisement

Answer

The following solution is appropriate for the question asked:

select Field1
      ,case when Field2<>1 then 0 else 1 end as Field2 
from 
    (select Field1
           ,ROW_NUMBER() over (partition by Field1 order by Field1) as Field2 from T1
    )u
 order by Field1 asc ,Field2  

Output :

Field1  Field2
A           0
A           0
A           1
B           0
B           1
C           1
D           1
E           0
E           0
E           0
E           1

Just keep in mind that this is not a good solution for big tables and operational data in your database

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement