可能重复:
How to get the record of a table who contains the maximum value?
我有一个如下所示的聚合查询:
SELECT TrainingID, Max(CompletedDate) as CompletedDate, Max(Notes) as Notes --This will only return the longest notes entry
FROM HR_EmployeeTrainings ET
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
哪个有效,并且大部分时间都返回正确的数据,但我注意到了一个问题。返回的Notes字段不一定与max(completedDate)来自的记录匹配。相反,它将是最长的字符串?或者具有最高ASCII值的那个?如果两个记录之间存在关联,SQL Server会做什么?我甚至都不确定。我想得到的是max(completedDate)记录中的notes字段。我应该怎么做呢?
答案 0 :(得分:23)
您可以使用子查询。子查询将获得Max(CompletedDate)
。然后,您再次获取此值并再次加入表格以检索与该日期关联的备注:
select ET1.TrainingID,
ET1.CompletedDate,
ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
select Max(CompletedDate) CompletedDate, TrainingID
from HR_EmployeeTrainings
--where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
group by TrainingID
) ET2
on ET1.TrainingID = ET2.TrainingID
and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID
答案 1 :(得分:6)
啊,是的,这就是它在SQL中的意图。你可以单独获得每列的最大值。您似乎希望从具有最大日期的行返回值,因此您必须选择具有最大日期的行。我更喜欢使用subselect来执行此操作,因为查询保持紧凑易读。
SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
AND CompletedDate in
(Select Max(CompletedDate) from HR_EmployeeTrainings B
where B.TrainingID = ET.TrainingID)
如果您还希望通过AntiRecID匹配,也应该在子选择中包含该内容。
答案 2 :(得分:3)
没有简单的方法可以做到这一点,但这样的事情会起作用:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
答案 3 :(得分:3)
单独评估每个MAX功能。因此MAX(CompletedDate)将返回最新CompletedDate列的值,MAX(Notes)将返回最大值(即字母最高值)。
您需要以不同方式构建查询以获得所需内容。这个问题实际上已经被多次询问和回答,所以我不再重复了:
How to find the record in a table that contains the maximum value?