Search code examples
sqlpostgresqlcasegreatest-n-per-groupwindow-functions

How to filter out records in a Case Statement using Min(date) in SQL?


I am working with a table similar to one below-
ID Type Size Date
1 new 10 1/30/2020 17:16
1 new 10 1/30/2020 17:25
3 old 15 1/30/2020 5:50
4 unused 20 1/30/2020 5:30
6 used 25 1/29/2020 18:30

I need my output to look like this-
ID Type Size Date Category
1 new 10 1/30/2020 17:16 A
1 new 10 1/30/2020 17:25 other
3 old 15 1/30/2020 5:50 B
4 unused 20 1/30/2020 5:30 C
6 used 25 1/29/2020 18:30 other

The condition for Category A needs to take in the first occurrence of the record. I am trying to do the following but it doesn't work well since min(date) gives an error-

select *,
case when type = 'new' and Size = '10' and min(date) then 'A'`
when type = 'old' and Size = '15' then 'B'
when type = 'unused' and Size = '20' then 'C'
else 'other'
end as category
from table1

Is there a workaround here without using a window function? (the table size is extremely large)


Solution

  • You can use row_number():

    select 
        t.*,
        case 
            when type = 'new' and Size = '10' 
                and row_number() over(partition by type, size, order by date) = 1
                then 'A'`
            when type = 'old' and Size = '15' then 'B'
            when type = 'unused' and Size = '20' then 'C'
            else 'other'
        end as category
    from table1