	select
  --L.Lpu_id,
  L.Lpu_Name as "Наименование мед. организации",
  L.Lpu_OGRN as "ОГРН",
  COALESCE(Stor.cntStorLB, 0)::int4 as "Количество складов подразделений",
  COALESCE(Stor.cntStorLS, 0)::int4 as "Количество складов отделений",
  COALESCE(cntDocRash, 0)::int4 as "Количество документов списания"
	from (
	  --- Список работающих служб и складов, ресурсов
	  select
	    L.Lpu_id,
	    COUNT(distinct case when s.Storage_pid is null then s.Storage_id end) as cntStorMain,
	    COUNT(distinct case when LB.LpuBuilding_id > 0 and ssl.LpuSection_id is null and ssl.LpuUnit_id is null then s.Storage_id end) as cntStorLB,
	    COUNT(distinct case when LS.LpuSection_id > 0 then s.Storage_id end) as cntStorLS,
	    SUM(case when LS.LpuSection_id > 0 then DU.cntDocRash end) as cntDocRash
	  from dbo.v_Lpu L
	  inner join dbo.v_StorageStructLevel ssl on L.Lpu_id = ssl.Lpu_id
	    and L.Lpu_begDate::date <= current_date 
	    and COALESCE(L.Lpu_endDate, current_date)::date >= current_date
	    and (COALESCE(L.Lpu_IsTest, 1) = 1)
	  inner join dbo.v_Storage s on s.Storage_id = ssl.Storage_id
	    and S.Storage_pid > 0 -- исключаем главные склады
	    and (coalesce(s.Storage_begDate,current_date)::date <= current_date )
	    and (coalesce(s.Storage_endDate,current_date)::date >= current_date )
	  left join dbo.v_LpuSection LS on LS.LpuSection_id = SSL.LpuSection_id
	  left join  dbo.v_LpuBuilding LB on LB.LpuBuilding_id = SSL.LpuBuilding_id 
	 -- 
	  LEFT JOIN LATERAL
	  (
	    select COUNT(DU.DocumentUc_id) as cntDocRash from dbo.DocumentUc DU
		where
			DU.Storage_sid = s.Storage_id
			and DU.DrugDocumentStatus_id in (2)
			and DU.DrugDocumentType_id in (2,22) -- select * from v_DrugDocumentType DDTD
			--and LS.LpuSection_id > 0
	  ) DU on true
	--  
	  where
	    LB.LpuBuilding_id > 0 and ssl.LpuSection_id is null and ssl.LpuUnit_id is null
	  or LS.LpuSection_id > 0
	  group by L.Lpu_id
	) as Stor
	inner join dbo.v_Lpu L on L.Lpu_id = Stor.Lpu_id
	;
