我正在尝试选择userName和groupId重复的所有行,而userId不是该userName / 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.groupId
and u.userId <> max(u1.userId)
group by userName, groupId
having count(*) > 1)
order by userName
但是,行:
and u.userId <> u1.max(userId)
给我一个错误。
执行此查询的正确方法是什么?
答案 0 :(得分:3)
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
答案 1 :(得分:1)
我应该这样做,我想:
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