Wygląda na to, że po prostu musisz zmodyfikować swój HAVING
klauzula, aby odfiltrować przypadki, w których balance
jest większa niż zero (Dłużnik) LUB balance
jest mniejsze od zera (wierzyciel).
Możesz także użyć warunkowego IF()
wyrażenia do określenia dr/cr w balance
kolumna.
Aby pozyskać dłużników tylko:
SELECT client_id,
Sum(Coalesce(CASE
WHEN action_type = 'dr' THEN amount
end, 0)) AS total_debits,
Sum(Coalesce(CASE
WHEN action_type = 'cr' THEN amount
end, 0)) AS total_credits,
Sum(Coalesce(CASE
WHEN action_type = 'cr' THEN amount
end, 0)) - Sum(Coalesce(CASE
WHEN action_type = 'dr' THEN
amount
end, 0)) AS total_debtors,
IF(Sum(Coalesce(CASE
WHEN action_type = 'cr' THEN amount
end, 0)) - Sum(Coalesce(CASE
WHEN action_type = 'dr' THEN
amount
end, 0)) > 0, 'dr', 'cr') AS balance
FROM tbl_balancesheet
GROUP BY client_id
HAVING balance = 'dr' AND total_debtors <> 0
Aby zdobyć wierzycieli tylko:
SELECT client_id,
Sum(Coalesce(CASE
WHEN action_type = 'dr' THEN amount
end, 0)) AS total_debits,
Sum(Coalesce(CASE
WHEN action_type = 'cr' THEN amount
end, 0)) AS total_credits,
Sum(Coalesce(CASE
WHEN action_type = 'cr' THEN amount
end, 0)) - Sum(Coalesce(CASE
WHEN action_type = 'dr' THEN
amount
end, 0)) AS total_debtors,
IF(Sum(Coalesce(CASE
WHEN action_type = 'cr' THEN amount
end, 0)) - Sum(Coalesce(CASE
WHEN action_type = 'dr' THEN
amount
end, 0)) > 0, 'dr', 'cr') AS balance
FROM tbl_balancesheet
GROUP BY client_id
HAVING balance = 'cr' AND total_debtors <> 0