首页 > 解决方案 > 查询每个产品和零件类型的最新记录日期(包括零件类型为空)

问题描述

我的数据库看起来像这样表名: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      ''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''

标签: sqldb2

解决方案


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;

推荐阅读