1

table name: transactions

customer debit credit
a 70 50
a 100 20
a 20 60
b 100 20
b 40 80
b 10 30
c 100 200
c 100 30
c 80 90
d 100 200
d 90 30
d 80 90
e 100 100
e 100 30
e 80 90

check who have positive or negative bal_type; if(total of debit-total of credit>0 ) positive else negative

I try below:

SELECT  CASE WHEN (SUM(debit)-SUM(credit))<0 THEN "negative" 
 ELSE "positive"
 END AS bal_type,
 customer
FROM 
    transactions
GROUP BY customer

MY OUTPUT:

bal_type customer
positive a
positive b
negative c
negative d
positive e

expecting:

bal_type customer
positive e,a,b
negative c,d

NOTE: bal_type is derived type column. positive customer name should be order by DESC using there SUM(debit)-SUM(credit). and negative customer name should be order by ASC using there SUM(debit)-SUM(credit).

2
  • Is it really intended to select "negative" for zero or is your logic incomplete? Commented Jan 15, 2023 at 12:33
  • Thanks Jonas, I got your point I update it. Commented Jan 17, 2023 at 4:23

1 Answer 1

3

You need 2 levels of aggregation and GROUP_CONCAT() aggregate function to concatenate the customers:

SELECT bal_type,
       GROUP_CONCAT(customer ORDER BY customer) AS customer
FROM (
  SELECT CASE WHEN SUM(debit)- SUM(credit) > 0 THEN 'positive' ELSE 'negative' END AS bal_type,
         customer
  FROM transactions
  GROUP BY customer
) AS t
GROUP BY bal_type;

See the demo.

Sign up to request clarification or add additional context in comments.

1 Comment

Please check updates into question. I need query according to these changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.