
DECLARE @PivotKolonlar VARCHAR(MAX)
SELECT @PivotKolonlar=  
COALESCE (@PivotKolonlar +',['+CAST(BAACIKLA AS VARCHAR) +']',
'['+CAST(BAACIKLA AS VARCHAR)+']')
FROM (SELECT DISTINCT(BAACIKLA) FROM ACARI ) AS DISTBAACIKLA
DECLARE @PVT nvarchar(max)
set @PVT=N'
SELECT * FROM (SELECT C.MUSKOD, C.BAACIKLA, (C.BORC-C.ALACAK) TUTAR FROM ACARI C LEFT JOIN AMUSTERI A ON A.MUSNO=C.MUSNO

) AS PIVOTDATA
PIVOT ( SUM(TUTAR) FOR BAACIKLA IN ('+ @PivotKolonlar+')
) AS PIVOTTABLO
'
EXECUTE
(@PVT)