SQL 服务器中的最大值和分组依据函数

Max and Group by functions in SQL Server

我的 sql 有点生疏了,我想知道是否有一个简单的解决方案来解决我的问题。我正在尝试使用 MAX ModifiedTime 获得两个唯一的 UUID。下面是我尝试尽可能简化的代码。我的目标是获得唯一的 UUID 及其 MAX ModifiedDate 以及其他两个关联的列 - 所需的输出 2 行。

SELECT [UUID],[Description],IsHLVE,ModifiedTime
FROM tblConstructSecureIntelProjectIncidents
WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
ORDER BY UUID,ModifiedTime

我尝试按所有列分组并执行 max 操作,但由于我的“描述”和“IsHLVE”具有不同的值,所以无法正常工作。

select [UUID],[Description],IsHLVE,MAX(ModifiedTime)
FROM tblConstructSecureIntelProjectIncidents
WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
GROUP BY [UUID],[Description],IsHLVE
ORDER BY UUID

我想我首先需要某种临时 table 然后再加入? 我想要的输出应该有两个唯一的 UUID,其最大日期包括所有关联的列。

也许是这样的?

SELECT * FROM tblConstructSecureIntelProjectIncidents AS t 
INNER JOIN (
 SELECT [UUID],MAX(ModifiedTime) AS LatestModifiedTime
 FROM tblConstructSecureIntelProjectIncidents
 WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
 GROUP BY [UUID]
) AS latest ON latest.UUID = t.UUID AND latest.LatestModifiedTime = t.ModifiedTime
ON latest.UUID

Sub-query 内连接会处理这个问题。

SELECT
    t1.uuid
    ,t1.Description
    ,t1.IsHLVE
    ,t1.modifiedtime
FROM tblConstructSecureIntelProjectIncidents as t1
INNER JOIN (
    SELECT
        MAX(modifiedtime) as modifiedtime
        ,uuid
    FROM tblConstructSecureIntelProjectIncidents
    GROUP BY uuid
) as s on t1.uuid = s.uuid and t1.modifiedtime = s.modifiedtime

这将获得每个 UUID 的最大修改时间:

select [UUID],MAX(ModifiedTime)
FROM tblConstructSecureIntelProjectIncidents
WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
GROUP BY [UUID]

现在您可以通过选择值并连接它们来获取所需的数据:

select [UUID],[Description],IsHLVE,MAX(ModifiedTime)
FROM tblConstructSecureIntelProjectIncidents tCSPI
INNER JOIN (
   select [UUID],MAX(ModifiedTime) as MMT
   FROM tblConstructSecureIntelProjectIncidents
   WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
GROUP BY [UUID]
) sub ON sub.UUID = tCSPI.UUID AND sub.MMT = tCSPI.ModifiedTime