2017-02-22 67 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