如何使用 SQL 中的 Min(date) 过滤掉 Case Statement 中的记录?
How to filter out records in a Case Statement using Min(date) in SQL?
我正在使用一个类似于下面的 table -
ID 类型大小日期
1 新 10 1/30/2020 17:16
1 新 10 1/30/2020 17:25
3 岁 15 1/30/2020 5:50
4 未使用 20 1/30/2020 5:30
6 使用 25 1/29/2020 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 1/30/2020 5:30 C
6 使用 25 1/29/2020 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
这里有不使用 window 函数的解决方法吗? (table尺寸非常大)
您可以使用 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
我正在使用一个类似于下面的 table -
ID 类型大小日期
1 新 10 1/30/2020 17:16
1 新 10 1/30/2020 17:25
3 岁 15 1/30/2020 5:50
4 未使用 20 1/30/2020 5:30
6 使用 25 1/29/2020 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 1/30/2020 5:30 C
6 使用 25 1/29/2020 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
这里有不使用 window 函数的解决方法吗? (table尺寸非常大)
您可以使用 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