尝试用一个 ID 将多行合并到一列中

Trying to consolidate multiple rows in one column with one ID

我正在尝试将具有相同 ID 但概念不同的多行合并为一行,使用“,”分隔符。

尝试了这段代码,但它给了我多个 ConceptsID 而不是一个

select distinct vc.Employeeid ,
(select distinct (STRING_AGG(cast(ConceptId as varchar(max)), ', ') WITHIN GROUP (ORDER BY ConceptId ASC)) from Concepts c1 where c.ConceptId = c1.ConceptId ) AS concept
from employee e 
 left join v_CurrentClasses vc on vc.[EmployeeId]=e.[EmployeeId]
Left JOIN ClassSchedules cs
   ON vc.ClassScheduleId = cs.ClassScheduleId
left JOIN ClassCategories cc
   ON cc.ClassCategoryId = cs.ClassCategoryId
LEFT JOIN ClassTypes ct
   ON ct.ClassTypeId = cc.ClassTypeId and ct.CSIServiceId = cc.ClassCategoryId
inner JOIN Concepts c
   ON c.ConceptId = ct.ConceptId
   left join [JobTitles] jt
   on jt.JobTitleId=e.JobTitleId
   inner join clubs cb
   on cb.clubid=vc.clubid
  --where e.date>= getdate()
  group by vc.Employeeid, c.ConceptId
  order by 1

这是即将到来的输出

Employeeid     conceptID
215             4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
217             2, 2, 2, 2, 2, 2, 2, 2, 2, 2
217             4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
217             8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
232             2, 2, 2, 2, 2, 2, 2, 2, 2, 2
240             23, 23
240             6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6
249             6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6
249             8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8

我想要这个输出

Employeeid     conceptID
215             4
217             2, 4, 8, 
232             2
240             23, 6
249             6, 8

你不能只取出 STRING_AGG 和 select 的不同值吗?

可能是这样的

SELECT 
    Employeeid
    ,STRING_AGG(cast(ConceptId as varchar(max)), ', ') WITHIN GROUP (ORDER BY ConceptId ASC) AS concept
FROM(
    select vc.Employeeid ,ConceptId
    from employee e 
     left join v_CurrentClasses vc on vc.[EmployeeId]=e.[EmployeeId]
    Left JOIN ClassSchedules cs
       ON vc.ClassScheduleId = cs.ClassScheduleId
    left JOIN ClassCategories cc
       ON cc.ClassCategoryId = cs.ClassCategoryId
    LEFT JOIN ClassTypes ct
       ON ct.ClassTypeId = cc.ClassTypeId and ct.CSIServiceId = cc.ClassCategoryId
    inner JOIN Concepts c
       ON c.ConceptId = ct.ConceptId
       left join [JobTitles] jt
       on jt.JobTitleId=e.JobTitleId
       inner join clubs cb
       on cb.clubid=vc.clubid
      --where e.date>= getdate()
      group by vc.Employeeid, c.ConceptId
    ) TB
order by 1