IF (EXISTS(Select * from sys.systable where LCase(table_name) = LCase('SalesSummaryAudit'))) THEN Drop view SalesSummaryAudit END IF GO create view DBA.SalesSummaryAudit as select UNP=INV.UNP, DocType=(if SO.DocType = 5 then 'Сторно' else if SO.DocType = 2 then 'Затворена' else 'Отворена' endif endif), DocNomer=convert(varchar(10),INV.InvoiceNo), StoreName=SO.StoreName, StartDocDate=convert(date,SO.MarkDateTime), StartDocTime=convert(time,SO.MarkDateTime), PosId=SO.WorkPlaceId, UserKod=INV.KodAdmin, TotalSumNoVat=DBA.CalcSaleInvoiceTotalNoVat(INV.InvoiceNo), TotalSumWithVat=DBA.CalcSaleInvoiceGrandTotal(INV.InvoiceNo), SumVAT=TotalSumWithVAT-TotalSumNoVAT, SumDiscounts=DBA.CalcSaleInvoiceSumDiscount(INV.InvoiceNo), EndDocDate=convert(date,INV.TrueInvoiceHour), EndDocTime=convert(time,INV.TrueInvoiceHour), PartnerCode=INV.Bulstat, PartnerName=INV.Whom, StoreN=SO.HotelID, InvoiceNumber=(if INV.trueinvoiceno <> 0 then convert(varchar(10),INV.TrueInvoiceNo) else null endif), InvoiceDate=(if INV.trueinvoiceno <> 0 then convert(date,INV.TrueInvoiceDate) else null endif), FiscalDeviceN=SO.FiscalDeviceN, UserN=INV.KodAdmin, Status='Затворена' from DBA.Invoices as INV join DBA.SaleOrders as SO on INV.UNP = SO.UNP and SO.ID = (select MIN(SaleOrders.ID) from DBA.SaleOrders where SaleOrders.UNP = INV.UNP) union all select UNP=SO.UNP, DocType=(if SO.DocType = 6 then 'Анулирана' else if SO.DocType = 2 then 'Затворена' else 'Отворена' endif endif), DocNomer=null, StoreName=SO.StoreName, StartDocDate=convert(date,SO.MarkDateTime), StartDocTime=convert(time,SO.MarkDateTime), PosId=SO.WorkPlaceId, UserKod=SO.UserID, TotalSumNoVat=DBA.CalcNotPayedSaleTotalNoVat(SO.ID), TotalSumWithVat=DBA.CalcNotPayedSaleGrandTotal(SO.ID), SumVAT=TotalSumWithVAT-TotalSumNoVAT, SumDiscounts=DBA.CalcNotPayedSaleSumDiscount(SO.ID), EndDocDate=convert(date,SO.MarkDateTime), EndDocTime=convert(time,SO.MarkDateTime,'hh:nn'), PartnerCode=null, PartnerName=null, StoreN=SO.HotelID, InvoiceNumber=null, InvoiceDate=null, FiscalDeviceN=SO.FiscalDeviceN, UserN=SO.UserID, Status='Отворена' from DBA.SaleOrders as SO where SO.DocType <> 5 and exists(select * from DBA.SaleOrderLines where SaleOrderLines.DocId = So.ID and SaleOrderLines.PayedQty <> SaleOrderLines.RegQty)