Попытка объединить несколько строк в одном столбце с одним идентификатором - PullRequest
0 голосов
/ 18 мая 2019

Я пытаюсь объединить несколько строк с одним и тем же идентификатором, но с разными концепциями в одной строке, используя разделитель ",".

Попробовал этот код, но он дает мне несколько 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

Ответы [ 2 ]

1 голос
/ 20 мая 2019

может быть что-то вроде этого

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
0 голосов
/ 18 мая 2019

Разве вы не можете просто взять STRING_AGG и выбрать другое значение?

...