
/****** Object:  View [dbo].[ApiCustomerFeaturesView]    Script Date: 13.09.2021 14:48:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE VIEW  [dbo].[ApiCustomerFeaturesView] as
select 
Parent Id,Parent ErpId, def.Name Name, feat.Data Value, def.ErpId  FeatureDefId, 
cust.Id ParentId, 0 GrandParentId, 3 ParentType,
Parent ParentDbId,
0 VendorId, kk.Time TS, 0 Status
 from dbo.Features feat
   JOIN  [dbo].[ApiFeaturesDefsView] def ON def.Name= feat.Name  and def.ObjectType =3
   JOIN dbo.ApiCustomers cust ON cust.ErpId = Parent 
   JOIN [dbo].[ApiDocumentFeatures] df ON 
    df.[FeatureDef] = def.ErpId and df.[ObjectType]=3
	JOIN 
	(  select k.ID , MAX(ci.Time)  Time from dbo.Kontrahenci k 
	 JOIN dbo.ChangeInfos ci ON ci.SourceGuid = k.Guid and ci.SourceTable = 'Kontrahenci' GROUP BY k.ID ) kk ON kk.ID = cust.ErpId
	
GO


