在SQL中按功能分组TOP 1

时间:2013-05-20 10:31:17

标签: sql

我有一个包含AppIdCommentTimeStamp列的表格。表可以包含相同AppId的多个条目。现在我要做的是通过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.

有人可以指出我如何使这项工作正确的方向

由于

1 个答案:

答案 0 :(得分: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

如果你没有那个,你需要更多的东西:

SELECT Comment, AppId
FROM comments
WHERE TimeStamp = (SELECT MAX(TimeStamp) FROM comments AS comments_inner WHERE comments_inner.AppId = comments.AppId)