2011-07-19 16 views
3

我想選擇其中用戶名和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) 

是給我的錯誤。

什麼是正確的方法來做這個查詢?

+1

A小調錯字,'u1.max(用戶ID)'應該是'MAX(u1.userId)',但我不認爲這將解決問題。 – rubish

+0

@ Rubish-謝謝!我會編輯它來修復錯字。 – dmr

回答

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 
+0

正在輸入一個類似的答案。 – rubish

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