Sql server SQL Server:在不同列上使用max返回id列
在我的表中,我有Sql server SQL Server:在不同列上使用max返回id列,sql-server,group-by,Sql Server,Group By,在我的表中,我有id、userId和points列。作为我查询的结果,我希望获得包含每个用户最高点的记录的id 根据我的经验(更多的是使用MySQL而不是SQL Server),我将使用以下查询来获得此结果: SELECT id, userId, max(points) FROM table GROUP BY userId 但是SQL Server不允许这样做,因为select中的所有列也应该位于GROUP BY中,或者是一个聚合函数 这是一种假设情况。我的实际情况要复杂得多 在SQL Ser
id
、userId
和points
列。作为我查询的结果,我希望获得包含每个用户最高点的记录的id
根据我的经验(更多的是使用MySQL而不是SQL Server),我将使用以下查询来获得此结果:
SELECT id, userId, max(points)
FROM table
GROUP BY userId
但是SQL Server不允许这样做,因为select中的所有列也应该位于GROUP BY
中,或者是一个聚合函数
这是一种假设情况。我的实际情况要复杂得多 在
SQL Server
Select * from
(
select Row_Number() over(partition by userId Order by points desc) Rn,*
From yourtable
) A
Where Rn = 1
使用
SQL Server中的ROW\u NUMBER
窗口功能
Select * from
(
select Row_Number() over(partition by userId Order by points desc) Rn,*
From yourtable
) A
Where Rn = 1