关联查询:select where条件不是max(内部查询中的条件)

发布于 2024-11-25 05:45:35 字数 549 浏览 3 评论 0原文

我试图选择 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)

给了我一个错误。

执行此查询的正确方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素罗衫 2024-12-02 05:45:35
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  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
甜心 2024-12-02 05:45:35

我认为这应该可以做到:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文