如何删除SQL表中的重复项并连接其他部分

时间:2015-11-02 10:47:20

标签: sql-server-2008 sql-server-2005

我们假设我有表示员工信息的DataTable / SQL表(MicroSoft SQL),例如

包含名字,姓氏,年龄,公司,年经验,学位

我想根据名字,姓氏,年龄

组合信息

公司,多年经验,学位必须进入相应的细胞

firstname   lastname   age   company   yearsofexperience      Degree

john         muller     21    IBM           4years            MBA   
jan          tonny      22,   MSoft         1years            MS
martin       tata       21    apple         2years            PHD
john         Muller     21    sony          3years            MBA
james        muller     21    IBM           4years            PHD   
jan          tonny      22    Telsa         1years            BS     
martin       tata       21    sun           2years            MBA
james        Muller     21    TCS           3years            BS

注意:MS SQL解决方案不是Mysql

请找到我删除重复行并在特定列

中使其他数据连续的方法

例如,在上面的示例中,我想要结合类似的其他3个条目中存在的信息

firstname   lastname   age   company            yearsofexperience      Degree

john      muller        21   IBM,sony,              4years,3years,        MBA,MBA   
jan       tonny         22,  MSoft,Telsa            1years,1years         MS,BS
martin    tata          21   apple,sun              2years,2years         PHD,MBA
james     muller        21   IBM,TCS               4years,3years          PHD,BS

对,我正在寻找实施此方法的最佳方法

如果我将表分成两个不同的表,它的好方法是什么?可以基于主键匹配。我们可以考虑其他条目吗?

请提前帮助我(+1)

2 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server,请尝试以下方法:

SELECT T1.firstname
,t1.lastname
,t1.age
,Company = SubString (( SELECT ', ' + T2.company 
FROM table_name as T2 
WHERE T1.firstname = T2.firstname
and t1.lastname = t2.lastname
and t1.age = t2.age 
FOR XML PATH ( '' ) ), 3, 1000) 

,yearsofexperience = SubString (( SELECT ', ' + T2.yearsofexperience 
FROM table_name as T2 
WHERE T1.firstname = T2.firstname
and t1.lastname = t2.lastname
and t1.age = t2.age 
FOR XML PATH ( '' ) ), 3, 1000) 

,yearsofexperience = SubString (( SELECT ', ' + T2.Degree 
FROM table_name as T2 
WHERE T1.firstname = T2.firstname
and t1.lastname = t2.lastname
and t1.age = t2.age 
FOR XML PATH ( '' ) ), 3, 1000) 

FROM table_name as T1 
GROUP BY T1.firstname, t1.lastname ,t1.age

参考:Create A Comma Delimited List From a Column in SQL Server

答案 1 :(得分:0)

您可以尝试SQL的group bygroup_concat

SELECT *,group_concat(company) as company,
group_concat(yearsofexperience) as yearsofexperience,
group_concat(Degree) as Degree  
from table group by firstname
group by lastname
group by age

了解更多信息请点击链接 Merge data in two row into one