SQL从表中选择不同的记录

时间:2013-11-06 09:09:06

标签: sql sql-server-2008 sql-server-2008-r2

我有一张这样的表:

enter image description here

期望的结果将是:

enter image description here

以下是解释:

结果应该只选择具有不同列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

为了获得所需的结果,脚本需要进行哪些更改?

2 个答案:

答案 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

Ranking Functions