问题
I am trying to select all the rows where the userName and groupId is duplicated, and the userId is not the max userId for that userName/groupId combination. Here is my code so far:
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
However, the line:
and u.userId <> u1.max(userId)
is giving me an error.
What is the right way to do this query?
回答1:
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
回答2:
This should do it, I think:
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
来源:https://stackoverflow.com/questions/6751249/correlated-query-select-where-condition-not-maxcondition-in-inner-query