Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a flag column that tells whether a column value varies within a group in SQL server

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading