 ALTER   proc [dbo].[sp_Fat_GelGid_KDV_Raporu]    
(@Tarih1 datetime,    
 @Tarih2 datetime)    
AS    
BEGIN   
    -- 1. DEVİR SATIRI (önceki tarihler)
    SELECT 
        0 AS SiraNo,
        @Tarih1 AS TARIH,
        NULL AS ISLEMNO,
        'Önceki Devir' AS IslemTuru,
        NULL AS No,
        'DEVİR TOPLAMI' AS Adi,
        ISNULL(SUM(Tutar),0) AS Tutar,
        ISNULL(SUM(KdvTutari),0) AS KdvTutari,
		FORMAT(@Tarih1, 'yyyy-MM') AS AyYil, 'Önceki Devir - ' + FORMAT(@Tarih1, 'yyyy-MM') IslemTuruTarih
    FROM (
        SELECT Tutar, KdvTutari     
        FROM GELGID 
        WHERE KdvTutari > 0 AND BAACIKLA = 'Gider' AND TARIH < @Tarih1

        UNION ALL     

        SELECT Tutar * -1, KdvTutari * -1    
        FROM GELGID 
        WHERE KdvTutari > 0 AND BAACIKLA = 'Gelir' AND TARIH < @Tarih1

        UNION ALL    

        SELECT Tutar, KdvTutari     
        FROM STOKHARDETBAG 
        WHERE FisTuru = 'F' AND KdvTutari > 0 AND GC = 'G' AND FaturaTarihi < @Tarih1

        UNION ALL    

        SELECT Tutar * -1, KdvTutari * -1     
        FROM STOKHARDETBAG 
        WHERE FisTuru = 'F' AND KdvTutari > 0 AND GC = 'C' AND FaturaTarihi < @Tarih1
    ) AS Devir
	UNION ALL
    SELECT *,FORMAT(TARIH, 'yyyy-MM') AS AyYil, IslemTuru + ' - ' + FORMAT(TARIH, 'yyyy-MM') IslemTuruTarih
   FROM (select 2 SiraNo,TARIH,ISLEMNO,BAACIKLA IslemTuru,MUSNO No,(GELGIDADI+'--' +GELGIDKODU) as Adi,Tutar,KdvTutari
     from GELGID where KdvTutari > 0 and BAACIKLA = 'Gider'    
   union all     
   select 4,TARIH, ISLEMNO,BAACIKLA,MUSNO,(GELGIDADI+'--' +GELGIDKODU),Tutar * -1 Tutar, KdvTutari * -1  KdvTutari     
     from GELGID     
    where KdvTutari > 0 and BAACIKLA = 'Gelir'    
   union all    
   select 1,FaturaTarihi, IslemNo,IslemTuru,CariNo,CariAdi,Tutar, KdvTutari   
     from STOKHARDETBAG     
    where FisTuru = 'F'  and KdvTutari > 0 and GC = 'G'    
   union all    
   select 3,FaturaTarihi, IslemNo,IslemTuru,CariNo,CariAdi,Tutar * -1 Tutar, KdvTutari * -1  KdvTutari     
     from STOKHARDETBAG     
    where FisTuru = 'F'  and KdvTutari > 0 and GC = 'C'    
    ) x where TARIH >= @Tarih1 and TARIH < @Tarih2 + 1     
     order by TARIH,IslemTuru   
END;    
