首页 > 解决方案 > 如何在 SQL 中使用 Min(date) 过滤掉 Case Statement 中的记录?

问题描述

我正在使用类似于下面的表格-
ID 类型大小日期
1 新 10 1/30/2020 17:16
1 新 10 1/30/2020 17:25
3 旧 15 1/30/2020 5:50
4 未使用20 2020 年 1 月 30 日 5:30
6 已使用 25 2020 年 1 月 29 日 18:30

我需要我的输出看起来像这样
-ID 类型大小日期类别
1 新 10 1/30/2020 17:16 A
1 新 10 1/30/2020 17:25 其他
3 旧 15 1/30/2020 5:50 B
4 未使用 20 2020 年 1 月 30 日 5:30 C
6 已使用 25 2020 年 1 月 29 日 18:30 其他

类别 A 的条件需要考虑记录的第一次出现。我正在尝试执行以下操作,但由于 min(date) 给出错误,因此效果不佳-

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

这里有没有使用窗口函数的解决方法?(桌子尺寸非常大)

标签: sqlpostgresqlcasegreatest-n-per-groupwindow-functions

解决方案


您可以使用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

推荐阅读