简单的SQL问题

时间:2010-07-21 12:25:20

标签: sql-server-2008 group-by

我无法相信我会如此坚持看似简单的查询。

我需要找回具有最大DateLogged值的给定项目的日志用户。我已经改写了一百万种方式,但这是表达我想要的最清晰的方式 -

SELECT L.User
FROM Log AS L
WHERE L.Id = 24
GROUP BY L.ProjectId
HAVING MAX(L.DateLogged) = L.DateLogged

但是,抛出“Column'Log.DateLogged'在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY子句中。”但我不希望它按DateLogged分组,也不希望它在聚合函数中。

3 个答案:

答案 0 :(得分:5)

我认为如果你使用L.Id = 24,你将只能获得一行。您应该按L.UserL.UserId过滤IMO,而不是L.Id

有关所有项目的列表,您可以这样做。

SELECT L.User, L.ProjectId, MAX (L.DateLogged) as DateLogged
FROM Log AS L
WHERE L.User = @YourUserNameGoesHere
GROUP BY L.User, L.ProjectId

对于您了解项目详细信息的单个项目,只需使用ORDER BY

SELECT TOP 1 L.User, L.DateLogged
FROM Log AS L
WHERE L.User = @YourUserNameGoesHere
AND L.ProjectId = @YourProjectIdGoesHere
ORDER BY L.DateLogged DESC

答案 1 :(得分:1)

我不确定这是否是您想要的,但也许这些例子可以帮助您。

在具有最大日期记录的项目@ProjectId上获取日志@LogId的用户:

SELECT TOP(1) L.User
FROM Log AS L
WHERE L.Id = @LogId AND L.ProjectId = @ProjectId
ORDER BY L.DateLogged DESC

为每个项目在日志@LogId中获取max DateLogged用户:

SELECT L.User, L.ProjectId
FROM Log AS L
WHERE L.Id = @LogId
  AND L.DateLogged = (
    SELECT MAX(L2.DateLogged) FROM Log AS L2
    WHERE L2.Id = L.Id AND L2.ProjectId = L.ProjectId
  )

答案 2 :(得分:0)

这类似于YRH的答案,但使用窗口函数(ROWNUMBER)而不是相关的子查询 - 这可能更有效:

DECLARE @ProjectId int
SELECT  L.[User],
        L.ProjectId
FROM    (SELECT L.[User],
                L.ProjectId
                ROW_NUMBER() OVER (PARTITION BY L.ProjectId ORDER BY DateLogged DESC) RN
         FROM   dbo.[Log] L
         WHERE L.Id = @LogId) L
WHERE   RN = 1