我有一个关系表:
EmployeeOptionRelation
EmployeeId OptionId
1 3
1 4
1 5
然后我有Option表:
Option
OptionId Name
3 A
4 B
5 C
我需要有这样的结果
EmployeeId Name
1 A,B,C
我做了类似的事情,但是没有工作,因为告诉我专栏OptionId需要成为小组的一部分,我知道如何做,但我不想重复同样的在主要的一个中查询一个,在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 :(得分: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