sql - 如何在 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
这里有没有使用窗口函数的解决方法?(桌子尺寸非常大)
解决方案
您可以使用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
推荐阅读
- c# - 在 EmguCV.3.1.0.1 中找到图像的傅里叶变换的最少代码是什么?
- python - 如何复制列表/数组中的特定值?
- jss - 如何在jss中选择第一个或最后一个孩子
- docker - 如何使用“&”创建 Dockerfile 以运行命令?
- reactjs - 使用默认值编辑反应播种中的输入字段
- javascript - 是否可以从具有跨源数据的元素中捕获?
- spring - org.hibernate.PropertyAccessException:无法通过反射设置字段值 [1] 值
- php - 在对象方法名称中连接 php 变量
- haskell - 在三便士 gui 画布上绘制图像
- macos - 将汇编代码放入宏中会在表达式错误中创建未知标记