BK1$REFAddress - Adresai
BK1$REFClient - Kontrahentai (Klientai / Pardavėjai)
BK1$THGoodSpec - Saskaitu detalizacija
THDocument - Dokumentai Saskaitos  / Pirkimai / Pardavimai bendras PRSF pardavimo saskaitos
BK1$THDocumentPRSF - Kas yra is THDocument israsytos saskaitos fakturos tik ID nurodytas


IMAS PARDAVIMO GENERAVIMAS IS APSKAITOS:
SELECT TOP (1000) thdoc.[IDC]
      ,thdoc.[DocTypeCode]
     
      ,thdoc.[Number]
      ,thdoc.[DocumentDate]
	  ,party.PartyCode,
	 
	  case when   clientas.PVMCode is NULL then 'ND' ELSE clientas.PVMCode end,
	 
	  case when  clientas.[EnterpriseTypeCode]='UAB' then 'UAB ' when  clientas.[EnterpriseTypeCode]='AB' then 'AB ' when  clientas.[EnterpriseTypeCode]='IĮ' then 'IĮ ' when  clientas.[EnterpriseTypeCode]='VŠĮ' then 'VŠĮ ' else '' end  +  generic.Name,
	  (select sum(Amount*Price)  from [CEPrekyba].[dbo].[BK1$THGoodSpec] where thdoc.IDC=DocID),
	   thdoc.[Summa]
	  
  FROM [CEPrekyba].[dbo].[BK1$THDocument] as thdoc,[CEPrekyba].[dbo].[BK1$THPartyAttribute] as party, BK1$REFGenericClient as generic,BK1$REFClient as clientas where clientas.code=generic.Code and generic.Code=PartyCode and thdoc.idc=party.DocID and PartyCode!='BK1' and  thdoc.DocTypeCode  like 'PRSF' and thdoc.DocumentDate>'2022-10-30'   order by thdoc.IDC desc 



MAXIMALUS NUMERIS:
SELECT 
       
max(cast(trim('DSG#' from [Number]) as int))  
  FROM [CEPrekyba].[dbo].[BK1$THDocument] where Number like 'DSG#[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' 




klientu sarasas su adresais:
SELECT TOP (1000) clientas.[Code]
      ,clientas.[EnterpriseTypeCode]
      ,clientas.[Parent]
      ,clientas.[Name]
	  ,case when clientas.[EnterpriseTypeCode]='MB' then 'MB ' when  clientas.[EnterpriseTypeCode]='UAB' then 'UAB ' when  clientas.[EnterpriseTypeCode]='AB' then 'AB ' when  clientas.[EnterpriseTypeCode]='IĮ' then 'IĮ ' when  clientas.[EnterpriseTypeCode]='VŠĮ' then 'VŠĮ ' else '' end  +  clientas.Name as realname
      ,clientas.[PlantCode]
      ,clientas.[PVMCode]
      ,clientas.[IsPerson]
	,addr.Name
	,PhoneNumber
  FROM [CEPrekyba].[dbo].[BK1$REFClient] as clientas  left join [CEPrekyba].[dbo].[BK1$REFClientAddress]  as clientaddr on ClientCode=Code left join [CEPrekyba].[dbo].[BK1$REFAddress] as addr on  AddressID=addr.IDC left join [CEPrekyba].[dbo].[BK1$REFPhone] as phone on phone.PartyCode=clientas.Code    order by Parent,realname