2014-08-27 60 views
-2

我已创建存储过程来选择数据和结果是:如何检查重复的列值?

ID NAME EMAIL 
1 John [email protected] 
2 Sam [email protected] 
3 Tom [email protected] 
4 Bob [email protected] 
5 Tom [email protected] 

,我想获得类似结果:

ID NAME EMAIL 
1 John [email protected] 
2 Sam [email protected] 
3 Tom [email protected], [email protected] 
4 Bob [email protected] 

所以,我该怎么办呢?

谢谢。

+0

ü要问什么? – Navneet 2014-08-27 08:23:16

+0

可能的重复[如何删除重复的行?](http://stackoverflow.com/questions/18932/how-can-i-remove-duplicate-rows) – Oliver 2014-08-27 15:00:31

回答

1
select 
    id, 
    name, 
    email 
from (
    select 
     rn = row_number() over(partition by name order by id asc), 
     id, 
     name, 
     email = stuff((select ', ' + convert(varchar, t2.email) 
         from @table_var t2 
         where t1.name = t2.name 
         for xml path('')) 
        ,1,2,'') 
    from @table_var t1 
    group by t1.id, t1.name 
)t 
where rn = 1 
order by id 
0

只是另一种方式,可以帮助

;WITH cte 
AS 
(
    SELECT Id 
    ,Name 
    ,Email 
    ,ROW_NUMBER() OVER(PARTITION BY Name,Email ORDER BY Id) AS rowNum 
    FROM Table 
) 
SELECT Id,Name,Email 
FROM cte 
WHERE rowNum=1; 
0

一种解决方案是:

select distinct e1.Name, 
(case when e2.Email is null then e1.Email else 
(case when e1.Email > e2.Email then e1.Email + ','+ e2.Email else e2.Email + ','+ e1.Email end) 
    end) from MyTable e1 
left join MyTable e2 on e1.Name = e2.Name and e1.Email <> e2.Email