在SQL Server中查找具有不同扩展名的重复记录

时间:2017-06-05 18:15:28

标签: sql-server

我有一个订阅表。样本记录:

  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R

我需要找到两个记录,因为订阅名称完全相同,但只是扩展名为R.

3 个答案:

答案 0 :(得分:1)

真的很糟糕的一次性代码写在这里并且未经测试,但是......

with cte As (Select Name, Id
From Subs
Where Name Not Like '%-R'
)
Select cte.Id, cte.Name, M.Name
From Subs As M
Join cte
On cte.Name + '-R' = M.Name

答案 1 :(得分:0)

您可以使用row_Number和partition by,如下所示:

Select * from (
    Select *, DupeRecords = Row_number() over(partition by replace([Subs Name],'-R','') order by Subs_Id)
       from #yoursubs
   ) a Where a.DupeRecords > 1

答案 2 :(得分:0)

根据您的最新标准:

  

所以,在上面的例子中,当我查询表时,我应该得到全部3   记录......第一个是基础记录,剩下的2个   是扩展 - SQL用户17分钟前

SELECT distinct
    0 as Subs_ID
    , CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
    , '' as Extension

FROM 
    subs

UNION

SELECT
    Subs_ID
    , CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
    , CASE WHEN SUBS_Name like '%-%' THEN RIGHT(SUBS_Name, LEN(SUBS_Name) - charindex('-',SUBS_Name)+1) ELSE '' END AS Extension

FROM 
    subs

将产生以下结果。一个“主”行,其仲裁ID号为“0”,该主人家族的每一行及其扩展名。

Subs_ID     SUB_NAME_MAIN        Extension
----------- -------------------- --------------------
0           SC FORM 124          
1           SC FORM 124          
2           SC FORM 124          -R