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

Cav*_*rob 0 sql t-sql sql-server sql-server-2005

我有一个表的行,存储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
Run Code Online (Sandbox Code Playgroud)

我想要返回以下行:

1234       100     44
1235       100     55
1238       400     88
1239       400     77
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*iwi 5

SQL Server 2005解决方案

select * from 
(
    select *, c = COUNT(*) over (partition by userID)
    from sampletable
) sq
where c > 1
Run Code Online (Sandbox Code Playgroud)

或者更一般地说

select *
from sampletable
where userid in
(
    select userid
    from sampletable
    group by userid
    having COUNT(*) > 1
)
Run Code Online (Sandbox Code Playgroud)

使用此示例

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
Run Code Online (Sandbox Code Playgroud)

输出是

serial_no  userid  enrollmentid
1234        100    44
1235        100    55
1238        400    88
1239        400    77
Run Code Online (Sandbox Code Playgroud)