[英]Return Most Recent Record group by 2 ID fields
I need to display the current status of a part ('approved' or 'not approved') I am setting up the status table as MaterialNo, ToolID, Status, Asofdate我需要显示零件的当前状态(“已批准”或“未批准”) 我将状态表设置为 MaterialNo、ToolID、Status、Asofdate
the idea is I may have several tools approved and several not approved.我的想法是我可能有几个工具被批准,而几个没有被批准。 I want to be able to see the most recent status for each tool but I don't want to see the historical status.
我希望能够看到每个工具的最新状态,但我不想看到历史状态。
have tried to use MAX(Asofdate) and group by MaterialNo, ToolID, and Status but it returns all of the status history for each.已尝试使用 MAX(Asofdate) 并按 MaterialNo、ToolID 和 Status 分组,但它会返回每个的所有状态历史记录。
SELECT MaterialNo, ToolID, PPAPStatus, MAX(Asof) as "AsOf"
FROM [MfgDataCollector].[dbo].[PPAPStatus]
Group By MaterialNo, ToolID, PPAPStatus
The Status Table has this data:状态表有以下数据:
MaterialNo ToolID Status Asofdate
52748677 1 Not approved 2019-10-10
52748677 1 approved 2019-10-13
52748677 2 approved 2019-10-14
I Want to see:我想看看:
MaterialNo ToolID Status Asofdate
52748677 1 approved 2019-10-13
52748677 2 approved 2019-10-14
One solution that usually has very good performance is a correlated subquery:通常具有非常好的性能的一种解决方案是相关子查询:
select p.*
from [MfgDataCollector].[dbo].[PPAPStatus] p
where p.asof = (select max(p2.asof)
from [MfgDataCollector].[dbo].[PPAPStatus] p2
where p2.MaterialNo = p.MaterialNo and
p2.ToolID = p.ToolID
);
For optimal performance, you want an index on (MaterialNo, ToolID, asof)
.为了获得最佳性能,您需要
(MaterialNo, ToolID, asof)
上的索引。
I like using ROW_NUMBER
with a TOP 1 WITH TIES
trick here:我喜欢在这里使用带有
TOP 1 WITH TIES
技巧的ROW_NUMBER
:
SELECT TOP 1 WITH TIES MaterialNo, ToolID, Status, Asofdate
FROM [MfgDataCollector].[dbo].[PPAPStatus]
ORDER BY ROW_NUMBER() OVER (PARTITION BY MaterialNo, ToolID ORDER BY Asofdate DESC);
Best option would be row_number()最好的选择是 row_number()
Select MaterialNo, ToolID,
PPAPStatus,AsofNow from (Select
MaterialNo, ToolID,
PPAPStatus,AsofNow, row_number()
over
(partition
by MaterialNo, ToolId, PPAStatus
order by
AsofNow desc) rn
FROM [MfgDataCollector].[dbo].
[PPAPStatus]
) t where t.rn=1
As of your requirement please find below query, Need your help.根据您的要求,请在下面查询,需要您的帮助。
;WITH CTE AS
(
SELECT *,ROW_NUMBER() OVER(PARTITION BY MaterialNo,ToolID ORDER BY Asofdate DESC) AS ROWNM
FROM [MfgDataCollector].[dbo].[PPAPStatus]
)
SELECT * FROM CTE WHERE ROWNM=1
Best option would be ROW_NUMBER() with no more complex logic with easy partition by fields.最好的选择是ROW_NUMBER()没有更复杂的逻辑,可以轻松按字段进行分区。
Please find below query for as of requirement.请在下面的查询中找到要求。
;WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY MaterialNo,ToolID ORDER BY Asofdate DESC) AS ROWNM
FROM [MfgDataCollector].[dbo].[PPAPStatus]
)
SELECT * FROM CTE WHERE ROWNM=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.