Det verkar som att du helt enkelt behöver ändra din HAVING
klausul, för att filtrera bort fall där balance
är antingen mer än noll (Gäldenär) ELLER balance
är mindre än noll (kreditör).
Du kan också använda villkorlig IF()
uttryck för att bestämma dr/cr i balance
kolumn.
För att få Gäldenärer endast:
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
För att få Kreditörer endast:
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