-1

I have the following table:

ID    Date
-------------------    
 1    Null
 1    1/2/2020
 2    Null
 2    12/2/2020
 3    Null

For every ID which has at least one non-null date, I need to classify as 'accounted'.

Result set should look like below:

id    Date      AccountFlag
----------------------------
 1    Null      Accounted
 1    1/2/2020  Accounted
 2    Null      Accounted
 2    12/2/2020 Accounted
 3    Null      Unaccounted
GMB
  • 216,147
  • 25
  • 84
  • 135
user10
  • 187
  • 2
  • 11

1 Answers1

1

You can use window functions to check if the same id has at least one non-null date, and a case expression to set the flag accordingly. Window aggregate functions come handy for this:

select id, date,
    case when max(date) over(partition by id) is not null
        then 'Accounted'
        ese 'Unaccounted'
    end as accountflag
from mytable

max() ignores null values, so it returns null if and only if all values in the partition are null. This would work just the same with min().

GMB
  • 216,147
  • 25
  • 84
  • 135