Sql 查找表中字段1相同而字段2不同的行
我有一个存储用户ID、注册ID和其他数据的表行。我想获得所有记录,其中有一个以上的用户ID和注册ID出现 样本数据:Sql 查找表中字段1相同而字段2不同的行,sql,sql-server,sql-server-2005,tsql,Sql,Sql Server,Sql Server 2005,Tsql,我有一个存储用户ID、注册ID和其他数据的表行。我想获得所有记录,其中有一个以上的用户ID和注册ID出现 样本数据: serial_no userID EnrollmentID ------------------------------- 1234 100 44 1235 100 55 1236 200 33 1237 300 66 1238 400 88 1239 400
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的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
它返回的是相反的结果集。@Caveatrob-两个查询都会精确返回示例中的4行result@Caveatrob从表中a=这是票?这甚至没有语法检查。就性能而言,我的答案中的第二个查询更快。对不起。。。我想是有点诵读困难的语法…应该来自表a:
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 )
SELECT a.* FROM Table1 a
INNER JOIN (
SELECT UserID FROM Table1 GROUP BY UserID HAVING COUNT(*) > 1
) b ON a.UserID = b.UserID