truncate table BatchCommandReferenceSummaryData

insert into BatchCommandReferenceSummaryData (BatchReferenceId,unitid,vendorid,unitorganizationid,PanelCount)
selecT b.id,
		case 
			when c.UnitOrganizationId is not null then u.UnitGuid
			when c.VendorId is not null then v.UnitGuid
			else null 
		end UnitGuidId,
		c.VendorId,
		c.UnitOrganizationId,
		count(1) panelCount
from BatchCommandReferences  b
	join BatchCommandPanels p on p.BatchCommandReferenceId=b.id
	join cptbl c on c.cpid = p.PanelId and c.Deleted is null
	left outer join VendorTbl v on v.VendorId=c.VendorId
	left outer join UnitOrganizations u on u.id=c.UnitOrganizationId
group by b.id,c.UnitOrganizationId,c.VendorId,u.UnitGuid,v.UnitGuid
order by 1,2 desc
