这是我的桌子
Guid
是唯一的。一个guid
仅与一个用户相关联。差异用户将没有相同的guid
。在这里,我希望所有上校都像Userid, guid, status, Errorcode and Retry
。我想从表中提取所有记录,其中该guid
的重试次数最大。
赞
该guid
的重试可以是0或1或2。
我的查询:
SELECT
Userid,
Guid,
Status,
ErrorCode,
Retry,
ROW_NUMBER() OVER(PARTITION BY Userid, Guid ORDER BY Retry) AS Row_Number
FROM UserInfo
如果我输入Row_Number=1
,该guid
只会获得第一。
我想为此guid
选择最大重试记录。
答案 0 :(得分:2)
ROW_NUMBER
实际上应该在这里起作用,但是您需要在通话中使用ORDER BY Retry DESC
:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY userid, Guid ORDER BY Retry DESC) rn
FROM UserInfo
)
SELECT userid, Guid, Status, ErrorCode, Retry
FROM cte
WHERE rn = 1;
如果您使用的是SQL Server,则实际上我们甚至可以不使用正式的子查询来编写查询:
SELECT TOP 1 WITH TIES userid, Guid, Status, ErrorCode, Retry
FROM UserInfo
ORDER BY ROW_NUMBER() OVER (PARTITION BY userid, Guid ORDER BY Retry DESC);
答案 1 :(得分:1)
这是您的查询,不需要用户row_number,MAX()
将解决此问题。
select t2.userid, t2.Guid, t2.Status, t2.ErrorCode, t1.maxRet from
UserInfo
inner Join
(select
max(Retry) AS maxRet, userid, Guid
from UserInfo
Group by userid, Guid) as t1
on t1.Guid = t2.Guid and t1.userid = t2.userid
答案 2 :(得分:1)
使用ORDER BY Retry desc
select * from
(
select userid,Guid,Status,ErrorCode,Retry,
ROW_NUMBER() OVER(Partition by userid,Guid ORDER BY Retry desc) AS Row_Number
from UserInfo
)A where Row_Number=1