2017-10-17 84 views
0

我有一個關係表:串連許多行成一個

EmployeeOptionRelation 
EmployeeId OptionId 
1    3 
1    4 
1    5 

然後我有選表:

Option 
OptionId Name 
3   A 
4   B 
5   C 

我需要有這樣的

EmployeeId Name 
1   A,B,C 

我結果做了這樣的事情,但不起作用,因爲它告訴我該列的OptionId需要成爲該組的一部分,我有一個想法如何做到這一點,但我d on't要重複相同的查詢之一,主要的一個,而另一個STUFF

SELECT em.EmployeeId, 
     STUFF(
      ( 
       SELECT '; ' + CONVERT(NVARCHAR, o.Name) 
        FROM [Option] o 
        WHERE o.OptionId = em.OptionId 
        FOR XML PATH, TYPE 
      ).value('.[1]','nvarchar(max)')   
      , 1 
      , 1 
      , '' 
    ) 
FROM [EmployeeOptionRelation] em 
GROUP BY em.EmployeeId 

回答

0

我通常用它像這裏面:

; with A 
as 
(
SELECT distinct em.EmployeeId, 
    (
     SELECT o.Name + ',' as 'data()' 
      FROM [Option] O 
      inner join [EmployeeOptionRelation] EM2 
       on o.OptionId = EM2.OptionId 
      where 
       EM2.EmployeeId = EM.EmployeeId 
      FOR XML PATH('') 
) as Name 
FROM [EmployeeOptionRelation] em 
) 
select 
    EmployeeId 
    , Name = left(Name, len(Name) - 1) 
from A