如何检查重复的列值?

时间:2014-08-27 08:19:26

标签: sql sql-server

我创建了存储过程来选择数据,结果是:

ID   NAME   EMAIL
1    John   asd@asd.com
2    Sam    asd@asd.com
3    Tom    asd@asd.com
4    Bob    bob@asd.com
5    Tom    asc@asd.com

我希望得到如下结果:

ID   NAME   EMAIL
1    John   asd@asd.com
2    Sam    asd@asd.com
3    Tom    asd@asd.com, asc@asd.com
4    Bob    bob@asd.com

所以,我该怎么做?

感谢。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

GROUP BY就是你追求的目标。

例如

SELECT name, email, count(email)
FROM table
GROUP BY name, email

将返回类似

的内容
1 John asd@asd.com 1

2 Sam asd@asd.com 1

3 Tom asd@asd.com 2

4 Bob bob@asd.com 1

添加

HAVING count(email) > 1

到最后将导致

1 Tom asd@asd.com 2

答案 2 :(得分: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;

答案 3 :(得分: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