SELECT cb.companyname AS çıkış,ct.companyname AS giriş, t.transactionvalue, t.transactiondate FROM ps_main_transactions AS t
LEFT JOIN ps_main_bank_accounts AS ba ON ba.accountid = t.accountid
LEFT JOIN ps_main_companies AS ct ON ct.companyid = t.companyid
LEFT JOIN ps_main_companies AS cb ON cb.companyid = ba.companyid
WHERE ba.companyid != t.companyid
ORDER BY t.transactiondate DESC



SELECT x.firma, SUM(x.cikis) AS alacak, SUM(x.giris) AS borc FROM (
SELECT cb.companyname AS firma,SUM(t.transactionvalue) AS cikis,0 as giris FROM ps_main_transactions AS t
LEFT JOIN ps_main_bank_accounts AS ba ON ba.accountid = t.accountid
LEFT JOIN ps_main_companies AS ct ON ct.companyid = t.companyid
LEFT JOIN ps_main_companies AS cb ON cb.companyid = ba.companyid
WHERE ba.companyid != t.companyid

GROUP BY cb.companyname 
UNION
SELECT ct.companyname AS firma,0 as giris,SUM(t.transactionvalue) AS cikis  FROM ps_main_transactions AS t
LEFT JOIN ps_main_bank_accounts AS ba ON ba.accountid = t.accountid
LEFT JOIN ps_main_companies AS ct ON ct.companyid = t.companyid
LEFT JOIN ps_main_companies AS cb ON cb.companyid = ba.companyid
WHERE ba.companyid != t.companyid

GROUP BY ct.companyname ) AS  x
GROUP BY x.firma


SELECT x.firma, SUM(x.alacak) AS alacak, SUM(x.borc) AS borc FROM (
SELECT ct.companyname AS firma, 0 AS borc , SUM(t.transactionvalue) AS alacak FROM ps_main_transactions AS t
LEFT JOIN ps_main_bank_accounts AS ba ON ba.accountid = t.accountid
LEFT JOIN ps_main_companies AS ct ON ct.companyid = t.companyid
LEFT JOIN ps_main_companies AS cb ON cb.companyid = ba.companyid
WHERE ba.companyid != t.companyid AND cb.companyname = 'Bilgegüç Ltd Şti'
GROUP BY ct.companyname
UNION
SELECT cb.companyname AS firma , SUM(t.transactionvalue) AS alacak , 0 AS borc FROM ps_main_transactions AS t
LEFT JOIN ps_main_bank_accounts AS ba ON ba.accountid = t.accountid
LEFT JOIN ps_main_companies AS ct ON ct.companyid = t.companyid
LEFT JOIN ps_main_companies AS cb ON cb.companyid = ba.companyid
WHERE ba.companyid != t.companyid AND ct.companyname = 'Bilgegüç Ltd Şti'
GROUP BY cb.companyname ) AS x
GROUP BY x.firma
