0

我有一张桌子,里面有AppId, Comment, TimeStamp. 表可以有多个相同的条目AppId。现在我要做的是通过Desc获取Top 1 Comment每个AppId订单。TimeStamp

我尝试过类似的东西

SELECT TOP 1 Comment, AppId FROM comments GROUP BY AppId

但这似乎不起作用,因为我收到错误

Column 'comments.Comment' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

有人可以为我指出正确的方向吗?

谢谢

4

1 回答 1

4

根据您的数据库引擎,您可以使用ROW_NUMBER().

SELECT Comment, AppId
FROM (
    SELECT Comment, AppId, ROW_NUMBER() OVER (PARTITION BY AppId ORDER BY TimeStamp DESC) AS GroupRowNumber
    FROM comments
) AS sub
WHERE GroupRowNumber = 1

如果你没有那个,你需要一些更hackish的东西:

SELECT Comment, AppId
FROM comments
WHERE TimeStamp = (SELECT MAX(TimeStamp) FROM comments AS comments_inner WHERE comments_inner.AppId = comments.AppId)
于 2013-05-20T10:34:51.047 回答