Correlated query: select where condition not max(condition in inner query)

夙愿已清 提交于 2019-12-23 16:09:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!