Skip to content
Advertisement

Create a Status column with 3 categories based on conditions in multiple columns in SQL

I have a table like this

I am trying to create a new column called “Status” based on the below conditions

Looking at the max and min of the date column,

  • Status = “No change”, if the value in the code column is the same for max(date) and min(date)
  • Status = “Increased”, if the value in the code column is ‘3025f‘ for min(date) and ‘3027f’ for max(date)
  • Status = “Decreased”, if the value in the code column is ‘3027f‘ for min(date) and ‘3025f’ for max(date)

My desired output is

I am trying to do it this way but not getting it right

Is there an efficient way that gets me the desired output? Can someone point me in the right direction?

Advertisement

Answer

Use first_value(). I’ll use a subquery to make the logic easier to follow:

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