Question

I am using SQLplus connecting to oracle database 12c

I have two tables, Customer and Account, where customers can have multiple accounts (one customer id, but multiple account types). I am trying to get the information on the customer with the largest amount of debt. Suppose we have the following information:

Customer table:

BSB#  Customer#  Name  Address
------------------------------
0123  123456     Adam  ABC st
0234  234566     Dave  CBC rd
0345  345667     Max   DSE st

Account table:

BSB#  Customer#  Type    Balance
---------------------------------
0123  123456     Saving  -2300
0123  123456     Credit  -500
0123  123456     iSaver  200
0234  234566     Saving  5000
0345  345667     Credit  -1500
0345  345667     iSaver  -200

The desired output:

Customer# Name   Address
-------------------------
123456    Adam   ABC St

I can print out the sum of everyone's account balance, but I am not sure how to print out just the information on the account with the lowest accumulated balance. I tried using MIN(SUM(A.Balance)) but I keep getting the error saying "not a single-group function". I wouldn't be surprised if I made a mistake somewhere.

I am relatively new to sql and this is what I have so far. Any advice or pointers would be nice...

SELECT C.Customer#, C.Name, Address, SUM(A.Balance)
FROM Customer C
RIGHT OUTER JOIN Account A
ON C.BSB# = A.BSB#
AND
C.Customer# = A.Customer#
GROUP BY C.Customer#, C.Name, Address;

Thanks!

Was it helpful?

Solution

The following will order the customers by the sum of the balances:

SELECT C.Customer#, C.Name, Address, SUM(A.Balance)
FROM Customer C JOIN
     Account A
     ON C.BSB# = A.BSB# AND
        C.Customer# = A.Customer#
GROUP BY C.Customer#, C.Name, Address
ORDER BY SUM(A.Balance);

If you want only one row, then that depends on the database. Here are some methods:

Change the select to:

SELECT TOP 1 . . . 

Add a limit clause to the end of the query:

LIMIT 1

Add a fetch clause to the end of the query:

FETCH FIRST 1 ROWS ONLY

And in Oracle, you can do this with a subquery:

SELECT *
FROM (SELECT C.Customer#, C.Name, Address, SUM(A.Balance)
      FROM Customer C JOIN
           Account A
           ON C.BSB# = A.BSB# AND
              C.Customer# = A.Customer#
      GROUP BY C.Customer#, C.Name, Address
      ORDER BY SUM(A.Balance)
     ) t
WHERE rownum = 1;

OTHER TIPS

U can use the folowing statement

    with MinAccounts as 
    ( 
      SELECT BSB#, Customer#, Balance
        FROM (
              SELECT BSB#, t.Customer# , sum(t.Balance) Balance, min(sum(t.Balance)) over () minBalance
                FROM Account t
               GROUP BY BSB#, Customer#
         ) d 
   WHERE Balance = minBalance) 
SELECT * 
  FROM MinAccounts a 
  JOIN Customer c ON a.BSB# = c.BSB#
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top