Изглежда, че просто трябва да промените своя HAVING
клауза, за да филтрирате случаи, когато balance
е или повече от нула (Длъжник) ИЛИ balance
е по-малко от нула (кредитор).
Можете също да използвате условен IF()
изрази за определяне на dr/cr в balance
колона.
За да получите Длъжници само:
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
За да получите Кредитори само:
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