Zdá se, že jednoduše potřebujete upravit HAVING
klauzule k odfiltrování případů, kdy balance
je buď více než nula (dlužník) NEBO balance
je menší než nula (věřitel).
Můžete také použít podmíněné IF()
výrazy k určení dr/cr v balance
sloupec.
Chcete-li získat dlužníky pouze:
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
Chcete-li získat Věřitele pouze:
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