我有一张这样的表:
期望的结果将是:
以下是解释:
结果应该只选择具有不同列UserName,RemarkID,CreatedBy和CreatedDate的最大ActivityCount列
我尝试过使用groupby但是出现了错误
Column 'ActivityCount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
这是使用group by
的SQL脚本select * from TableName group by UserName, RemarkID, CreatedBy, CreatedDate
为了获得所需的结果,脚本需要进行哪些更改?
答案 0 :(得分:4)
试试这个:
SELECT UserName, RemarkID, CreatedBy, CreatedDate, MAX(ActivityCount)
FROM TableName
GROUP BY UserName, RemarkID, CreatedBy, CreatedDate
答案 1 :(得分:3)
最简单的方法是使用ROW_NUMBER
和CTE:
WITH CTE AS
(
SELECT t.*,
RN = ROW_NUMBER() OVER (PARTITION BY UserName, RemarkID, CreatedBy, CreatedDate
ORDER BY ActivityCount DESC)
FROM dbo.TableName t
)
SELECT * FROM CTE WHERE RN = 1
如果您想查看每个组ActivityCount
最高的所有记录(如果有多个),您可以使用DENSE_RANK
代替ROW_NUMBER
。