34,588
社区成员
发帖
与我相关
我的任务
分享
if object_id('[T1]') is not null drop table [T1]
create table [T1]([id] varchar(4),[cpid] varchar(2))
insert [T1]
select '0001','01' union all
select '0001','01' union all
select '0003','01' union all
select '0015','03' union all
select '0015','05' union all
select '0018','07' union all
select '0018','09'
select * from t1 as a where 2<=
(select count(*) from (
(select distinct * from t1 where a.id=id )
) as tt)
/*
id cpid
---- ----
0015 03
0015 05
0018 07
0018 09
*/
create table #t1
(id nvarchar(10), cpid nvarchar(10))
insert #t1 select '0001', '01'union all
select '0001', '01'union all
select '0003', '01'union all
select '0015', '03'union all
select '0015', '05'union all
select '0018', '07'union all
select '0018', '09'
select * from #t1 as t1
where exists(select 1 from #t1 as t2 where t2.id=t1.id and t2.cpid<>t1.cpid)
CREATE TABLE #temp
(
id VARCHAR(10),
cpid VARCHAR(10)
)
INSERT #temp
select '0001', '01' union all
select '0001', '01' union all
select '0003', '01' union all
select '0015', '03' union all
select '0015', '05' union all
select '0018', '07' union all
select '0018', '09'
go
--SQL:
SELECT A.* FROM #temp A
INNER JOIN
(
SELECT id FROM #temp
GROUP BY id
HAVING COUNT(*) = COUNT(DISTINCT cpid) AND COUNT(*) > 1
) B
ON A.id = B.id
/*
0015 03
0015 05
0018 07
0018 09
*/
--> 测试数据:[T1]
if object_id('[T1]') is not null drop table [T1]
create table [T1]([id] varchar(4),[cpid] varchar(2))
insert [T1]
select '0001','01' union all
select '0001','01' union all
select '0003','01' union all
select '0015','03' union all
select '0015','05' union all
select '0018','07' union all
select '0018','09'
select * from [T1]
SELECT id ,cpid FROM T1 WHERE id IN (SELECT id FROM (SELECT DISTINCT id ,cpid FROM T1)B GROUP BY id HAVING COUNT(1) >=2)
/*
id cpid
0015 03
0015 05
0018 07
0018 09*/