2012-10-17 44 views
16

可能重复:
How to get the record of a table who contains the maximum value?SQL选择最大(日)和对应的值

我有类似下面的汇总查询:

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

CompletedDate不是日期时间吗? – Frobzig

+0

这是一个DateTime。这个领域没有问题,但有了Notes。 – MAW74656

+0

max(completedDate)'的最大音符或每个音符? – Marc

回答

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 
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 
+0

你的语法对于你的子查询是错误的,你缺少一个'FROM'子句。 – Taryn

3

每个MAX函数都是单独评估的。因此,MAX(CompletedDate)将返回最新的CompletedDate列的值,MAX(Notes)将返回最大值(即按字母顺序排列的最高值)。

您需要以不同的方式构建您的查询以获得您想要的内容。这个问题实际上已经被问和回答了好几次,所以我就不再重复了:

How to find the record in a table that contains the maximum value?

Finding the record with maximum value in SQL

+1

如果之前已经回答了很多次这个问题,那么正确的做法是投票结束为“完全重复” – Tony

+0

Thx,我现在已经完成了。 – Marplesoft

5

是啊,这是它是如何打算的SQL。你分别得到每列的最大值。看起来你想从最大日期的行中返回值,所以你必须选择最大日期的行。我更喜欢用子查询来做到这一点,因为查询保持简洁易读。

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进行匹配,你也应该在子选择中包含它。