
update x
set x.paneldevicetypes = ag
from BatchCommandReferences x 
	join (
select id,string_agg(devicetype,',') ag
from (
selecT b.Id,c.devicetype
from BatchCommandReferences  b
	join BatchCommandPanels p on p.BatchCommandReferenceId=b.id
	join CpTbl c on c.cpid=p.PanelId
group by b.id,c.DeviceType
) c
group by id) z on z.Id=x.id