我需要获取具有重复
的行的行IDSelect Name from table1 group by Name having count(1) > 1
表1
ID | Name | ClientID
----------------------------
01 | John | 01
02 | Sam | 01
03 | Sue | 01
04 | John | 02
05 | John | 01
唯一的问题是它只会返回Name而不是列的ID,因为我在同一个表上有多个客户端,并且我不想将其他客户端的名称计为重复项。< / p>
那么有没有办法在表中查找重复数据并返回行的ID,以便我可以在另一个查询中使用这些ID?
回答我修改了
感谢每一个人对我的答案,这是对我标记为答案的答案的修改。
select t1.*
from (select count(*) over (partition by entityname) as cnt ,t1.*
from table1 t1 where ClientID = 1
) t1
where cnt > 1 and ClientID = 1 order by cnt;
答案 0 :(得分:1)
使用窗口功能:
select t1.*
from (select t1.*, count(*) over (partition by name) as cnt
from table1 t1
) t1
where cnt > 1;
count(*) over (partition by name)
计算每个名称的行数。但是,它通过在每行上附加计数来实现,而不是通过减少行数。这是选择行所需的信息。
答案 1 :(得分:1)
Select Name, min(ID) ROWID From table1 Group BY Name Having Count(ID)>1
min(ID)此处将返回第一次ID出现在副本中,而Count(ID)&gt; 1将过滤掉您有重复项的行。
祝你好运!
答案 2 :(得分:0)
查看欺骗的链接
Declare @Yourtable table (ID varchar(25),Name varchar(50),Client_ID varchar(25))
Insert into @Yourtable values
('01','John','01'),
('02','Sam' ,'01'),
('03','Sue' ,'01'),
('04','John','02'),
('05','John','01')
Select A.*
,B.Dupes
From @YourTable A
Cross Apply (Select Dupes=(Select Stuff((Select Distinct ',' + cast(ID as varchar(25))
From @YourTable
Where ID<>A.ID and Name=A.Name
For XML Path ('')),1,1,'')
)
) B
Where Dupes is not null
返回
ID Name Client_ID Dupes
01 John 01 04,05
04 John 02 01,05
05 John 01 01,04
答案 3 :(得分:0)
您可以像这样查询
;WITH cte_duplicates
AS (SELECT
id, name, client_id,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY id) AS rc
FROM @Yourtable)
SELECT
id, name, client_id
FROM cte_duplicates
WHERE rc > 1
答案 4 :(得分:0)
如果您想根据名称和ClientId提交重复项,请使用以下查询。
; with cte_1
as (select *, count(*) over (partition by name,client_id order by ID) as dups
from table1 )
Select *
From cte_1
where dups> 1;