1

我有一个表,其中有两列重复。

id name  classname description 
-----------------------------
1  a     aa        aa:abcd  
2  a     Unknown   Unknown 
3  b     bb        unknown 
4  c     cc        abcd 

现在我有一个选择查询,其中我必须过滤掉所有重复项,我的描述显示为标识符,我的结果应该是这样的,

id name identifier
-----------------
1  a   aa
2  b   NULL 
3  c   NULL

其中所有没有“:”作为其字符索引的描述应显示为 NULL 或 Unknown as Null。

我正在使用下面的选择查询来过滤“名称”​​列中的重复项,但是我无法使用相同的查询进行描述,因为我使用案例来获取结果以修剪我的描述“aa:abcd” '到aa

    select distinct 
           id,
           (select top 1 name 
             from table1 t 
            where t.name = t1.name 
            order by case t1.classname 
                        when 'Unknown Tag Class' then 0 
                        else 1 
                     end
            ) name,
            (case when charindex(':',Description)> 0
               then substring(Description,1,(charindex(':',Description)-1)) 
            end
            ) as Identifier
    from table1  t1

In the above query I want to modify the case statement of description so that i can filter duplicates and also trim the values like "aa:abcd" to "aa" and put them in identifier column.

Need help on this.


this is the query i am using 

IF  EXISTS (SELECT * FROM sys.objects     WHERE object_id = OBJECT_ID(N'[dbo].[EXEC_REP_TransposedTagAttributes]')
AND type in (N'U'))
BEGIN
   select distinct 
      [Att : 42674] as TagID
       ,Tagname
       ,isnull([Att : 14591],'-') as OriginatingContractor
       ,isnull([Att : 14594],'-') as System
      ,(case when charindex(':',TargetName)> 0 then 
    substring(TargetName,(charindex(':',TargetName)+1),len(TargetName)) 
   end) as SystemDescription
,(case when charindex(':',TagClassDescription)> 0 then 
    substring(TagClassDescription,1,(charindex(':',TagClassDescription)-1)) 
   end) as TagIdentifier
from EXEC_REP_TransposedTagAttributes t1
LEFT JOIN (SELECT SourceName, TargetName FROM EXEC_REP_Associations WHERE AssociationType = '3' and TargetClassName = 'SUB SYSTEM') b ON TagName = b.SourceName
where tagname='ZIH-210053' Order by [Att : 42674]
END
ELSE
 select 'Reporting Database is being refreshed, please wait.' as errMsg

我得到的结果是

TagID Tagname OriginatingContractor System SystemDescription TagIdentifier

2609005 ZIH-210053 现代重工 (Topsides) 210 Slugcatcher NULL 2609005 ZIH-210053 现代重工 (Topsides) 210 Slugcatcher ZIH

还有一些行的标签标识符为 null 并且没有重复项

4

1 回答 1

0
select id,name,
       CASE WHEN charindex(':',description)>0
         THEN LEFT(description,charindex(':',description)-1) 
         ELSE NULL
       END as identifier

from t as t1
where description like '%:%'
      or NOT EXISTS (select * from t where t.id<>t1.id and t.name=t1.name);

SQLFiddle 演示

于 2013-10-18T10:58:48.310 回答