sql - 查询每个产品和零件类型的最新记录日期(包括零件类型为空)
问题描述
我的数据库看起来像这样表名:Process_Result
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Product_No '' Part_Type '' INPUT_DATE '' PROCESS_CD ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' 111111 '' '' 01/05/2021 '' First ''
'' 111111 '' M '' 10/05/2021 '' Five ''
'' 111111 '' M '' 01/05/2021 '' Four ''
'' 111111 '' N '' 03/05/2021 '' First ''
'' 222222 '' '' 02/05/2021 '' Second ''
'' 222222 '' '' 05/05/2021 '' Third ''
'' 222222 '' N '' 10/05/2021 '' First ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
一起选择产品和零件类型并仅选择最大日期行
我想要的结果:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Product_No '' Part_Type '' INPUT_DATE '' PROCESS_CD ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' 111111 '' '' 01/05/2021 '' First ''
'' 111111 '' M '' 10/05/2021 '' Five ''
'' 111111 '' N '' 03/05/2021 '' First ''
'' 222222 '' '' 05/05/2021 '' Third ''
'' 222222 '' N '' 10/05/2021 '' First ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
现在我的查询如下所示:
SELECT product_no,
part_type,
input_time,
process_cd
FROM process_result AS A
WHERE A.input_time = (SELECT Max(input_time)
FROM process_result AS B
WHERE A.product_no = B.product_no
AND A.part_type = B.part_type)
它不显示A表的空数据等于B表的空数据我已经在谷歌上搜索过,我仍然不明白。现在结果是这样的:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Product_No '' Part_Type '' INPUT_DATE '' PROCESS_CD ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' 111111 '' M '' 10/05/2021 '' Five ''
'' 111111 '' N '' 03/05/2021 '' First ''
'' 222222 '' N '' 10/05/2021 '' First ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
解决方案
Product_No 和 Part_Type 在这里看起来很自然,尝试使用 row_number()...
select Product_No, Part_Type, Input_Date, Process_CD
from (
select Product_No, Part_Type, Input_Date, Process_CD,
rn = row_number() over (partition by product_no, part_type order by Input_Date desc)
from dbo.Process_Result
) src
where rn=1;
推荐阅读
- c# - 在加载新场景之前我必须卸载场景吗?
- ios - 如何从 tel 打开电话:使用 Swift 的 WebKit iOS 应用程序的 url 链接
- swift - 请评价你的 Swift MVVM 实现
- flutter - Flutter - 如何创建一个框架,我可以在其中拥有调试版本和生产版本,其中调试版本可以通过某种方式选择测试环境
- r - 根据 R 中数据集中进一步向下的观察创建变量
- c++ - 在 C 中实现的平均 DC 估计器的解释
- javascript - 如何修复 javascript 的运行方式并整合页面在所有类型选项卡中的加载方式
- python - 将 pandas DataFrame 中的日期时间值与特定的 data_time 值进行比较并返回壁橱
- ios - 当应用程序因缺乏最近使用而被 iOS 自动卸载时,本地 Realm DB 会发生什么情况?
- python - Python Serverless (SLS):Runtime.ImportModuleError:无法导入模块