Sql 相关查询:选择条件不最大的位置(内部查询中的条件)
我试图选择用户名和groupId重复的所有行,并且userId不是该用户名/groupId组合的最大userId。以下是我目前的代码:Sql 相关查询:选择条件不最大的位置(内部查询中的条件),sql,select,sql-server-2000,aggregate-functions,exists,Sql,Select,Sql Server 2000,Aggregate Functions,Exists,我试图选择用户名和groupId重复的所有行,并且userId不是该用户名/groupId组合的最大userId。以下是我目前的代码: select * from userTable u where exists (select * from userTable u1 where userName <> '' and userName is not null and u.userName = u1.userName and u.groupId = u1
select *
from userTable u
where exists
(select *
from userTable u1
where userName <> '' and userName is not null
and u.userName = u1.userName and u.groupId = u1.groupId
and u.userId <> max(u1.userId)
group by userName, groupId
having count(*) > 1)
order by userName
然而,该行:
and u.userId <> u1.max(userId)
给我一个错误
做这个查询的正确方法是什么?我认为应该这样做:
SELECT u.*
FROM (
SELECT userName, groupId, MAX(userId) AS maxId
FROM userTable
GROUP BY
userName, groupId
HAVING COUNT(*) > 1
) q
JOIN userTable u
ON u.userName = q.userName
AND u.groupId = q.groupId
AND u.userId <> q.maxId
select t.*
from dbo.UserTable t
join ( select userName , groupID , maxUserID = max(userID)
from dbo.UserTable x
group by userName , groupID
having count(*) > 1
) dupes on dupes.userName = t.userName
and dupes.groupID = t.groupID
and dupes.maxUserID > t.userID
一个小的输入错误,u1.maxuserId应该是maxu1.userId,但我认为这不能解决问题。@Rubish-谢谢!我会编辑它来修正打字错误。我正在打一个类似的答案。