我有一个历史记录表(如日志),记录部分的更改:
TransactionID Part ID Description Last Updated
1 1 Fixed O-ring 2006-03-14 20:00:04.700
2 2 Replaced coil 2009-01-02 20:00:04.700
3 1 Replaced coil 2009-01-02 20:00:04.700
4 1 Replaced LED 2002-08-20 20:00:04.700
5 2 Sealed leakage 2007-03-08 20:00:04.700
6 3 Replace connector 2004-05-16 20:00:04.700
我有另一张表格,会显示每个部分ID代表什么,但这不是我现在面临的问题。我需要编写一个查询,返回对每个部分进行的最新维护。所以在这种情况下,我的预期输出将是:
TransactionID Part ID Description Last Updated
2 2 Replaced coil 2009-01-02 20:00:04.700
3 1 Replaced coil 2009-01-02 20:00:04.700
6 3 Replace connector 2004-05-16 20:00:04.700
说明:例如,部件ID#1的最新维护工作已于2009-01-02 20:00:04.700完成,依此类推。
我已经尝试了SELECT DISTINCT
,但它不会起作用,因为基本上每一行都会有所不同。我完全没有线索。如果我使用MAX(Last Updated)
,它将只返回整个表的一行。
已编辑:无论如何,我不允许使用动态查询。
答案 0 :(得分:3)
SELECT TransactionID
,PartID
,[Description]
,[Last Updated]
FROM (
SELECT TransactionID
,PartID
,[Description]
,[Last Updated]
,ROW_NUMBER() OVER (PARTITION BY [PartID] ORDER BY [Last Updated] DESC) RN
FROM TableName
)A
WHERE A.RN = 1
或者您可以使用CTE
;WITH CTE AS
(
SELECT TransactionID
,PartID
,[Description]
,[Last Updated]
,ROW_NUMBER() OVER (PARTITION BY [PartID] ORDER BY [Last Updated] DESC) RN
FROM TableName
)
SELECT TransactionID
,PartID
,[Description]
,[Last Updated]
FROM CTE
WHERE A.RN = 1
答案 1 :(得分:1)
select
TransactionID, PartID, Description, LastUpdated
from
History H
where
LastUpdated =
(
select
max(LastUpdated)
from
History
where
PartID = H.PartID
)
答案 2 :(得分:1)
这是我怎么做的
;WITH CTE AS
(
Select PartId, MAX(LASTUPDATED) as 'MAXX' from part group by PartId
)
Select TransActionId, p.PartId, Description, p.LASTUPDATED
from Part p
inner join CTE on p.LastUpdated = CTE.MAXX
and p.PartId = CTE.PartId
答案 3 :(得分:0)
SELECT t.TransactionID, t.PartID, t.Description, t.LastUpdated
FROM History t
JOIN (SELECT PartID, MAX(TransactionID)
FROM History
GROUP BY PartID) t2 ON t.PartID = t2.PartID
AND t.TransactionID = t2.TransactionID
也可以。