2017-02-22 36 views
1

连接多个表后,我有一些结果仅在一列中有所不同。是否有一种“简单”的方式将这些差异压缩到一行?SQL服务器 - 在连接的一列中连接几个列值

例如,让我们假设后加入我有这样的事情:

id | project | date  | Oranges | Apples | Name 
1  xaxa 1.1.2000 yes  yes  Tom 
1  xaxa 1.1.2000 yes  yes  Bob 
1  xaxa 1.1.2000 yes  yes  Jan 

,我想有这样的事情:

id | project | date  | Oranges | Apples | Name 
1 xaxa  1.1.2000 yes  yes  Tom, Bob, Jan 

不过初学者在这里,请温柔: )

+1

可能出现[模拟Microsoft SQL Server 2005中的组\ _concat MySQL函数?](http:// stackoverf low.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005) –

回答

0
select id, project, date, Oranges, Apples 
    , Names = stuff((
    select distinct ', '+i.Name 
     from t as i 
     where i.id  = t.id 
     and i.project = t.project 
     and i.date = t.date 
     and i.Oranges = t.Oranges 
     and i.Apples = t.Apples 
     order by i.Name 
     for xml path (''), type).value('.','varchar(max)') 
    ,1,2,'') 
from t 
group by id, project, date, Oranges, Apples