I want to create a flag column that tells whether the values in a certain columns are identical when they are grouped by another column. For example, the data looks like this:
ID City Code
AB123 London CA1
AB123 New York CA1
CD321 Paris CA1
CD321 Tokyo DW2
I’d like to add a new column that tells whether the values of CODE vary within a group when the data is grouped by ID.
ID City Code Flag
AB123 London CA1 0
AB123 New York CA1 0
CD321 Paris CA1 1
CD321 Tokyo DW2 1
I tried to assign a row number by using partion by but it simply assins a row number by a group.
SELECT ID, City, Code,
ROW_NUMBER() OVER (PARTITION BY CODE, ID ORDER BY ID) as Flag
FROM table
ORDER BY ID
>Solution :
You’re right to consider a window function, if the minimum value in the window equals the maximum value in the window, they are the same:
select *,
case when Min(code) over(partition by id)
= max(code) over(partition by id) then 0 else 1 end Flag
from t;