查找表中的行,其中field1相同且字段2不同

时间:2011-02-01 18:51:24

标签: sql sql-server sql-server-2005 tsql

我有一个表的行,用于存储UserID,EnrollmentID和其他数据。我想获取所有记录,其中出现多个UserID和EnrollmentID。

示例数据:

serial_no  userID  EnrollmentID
-------------------------------
1234       100     44
1235       100     55
1236       200     33
1237       300     66
1238       400     88
1239       400     77

我想要返回以下行:

1234       100     44
1235       100     55
1238       400     88
1239       400     77

编辑:为了澄清,我希望所有存在用户ID的行具有不同的注册ID

3 个答案:

答案 0 :(得分:5)

SQL Server 2005解决方案

select * from 
(
    select *, c = COUNT(*) over (partition by userID)
    from sampletable
) sq
where c > 1

或更一般地

select *
from sampletable
where userid in
(
    select userid
    from sampletable
    group by userid
    having COUNT(*) > 1
)

使用此示例

create table sampletable (serial_no int, userid int, enrollmentid int)
insert sampletable select 1234 ,100 ,44
insert sampletable select 1235 ,100 ,55
insert sampletable select 1236 ,200 ,33
insert sampletable select 1237 ,300 ,66
insert sampletable select 1238 ,400 ,88
insert sampletable select 1239 ,400 ,77

输出

serial_no  userid  enrollmentid
1234        100    44
1235        100    55
1238        400    88
1239        400    77

答案 1 :(得分:3)

select a.serial_no, a.userID, a.EnrollmentID  
from a tableA 
where a.userID in (  
SELECT DISTINCT a.userID
FROM tableA  a, tableA  b
WHERE a.userID = b.userID
AND a.EnrollmentID <> b.EnrollmentID )

答案 2 :(得分:1)

SELECT a.* FROM Table1 a
INNER JOIN (
  SELECT UserID FROM Table1 GROUP BY UserID HAVING COUNT(*) > 1
) b ON a.UserID = b.UserID