GROUP BY ROLLUP - это путь.Это позволяет создавать все возможные промежуточные итоги и общий итог.После объединения данных вы просто оставили соединение с таблицей клиентов, чтобы получить имена first_name и last_name.Обязательно выполните левое объединение, чтобы не потерять общий итог
--SAMPLE TABLES AND TEST DATA
CREATE TABLE WGB_TRANSACTION (
CUSTOMER_NUMBER VARCHAR2(7),
ACCOUNT_TYPE NUMBER(1),
TRANSACTION_AMOUNT NUMBER,
TRANSACTION_TYPE VARCHAR2(1)
);
CREATE TABLE WGB_CUSTOMER (
CUSTOMER_NUMBER VARCHAR2(7),
FIRST_NAME VARCHAR2(30),
SURNAME VARCHAR2(30)
);
INSERT INTO WGB_CUSTOMER VALUES ( '123', 'John','Smith');
INSERT INTO WGB_CUSTOMER VALUES ( '456', 'James','Anderson');
INSERT INTO WGB_TRANSACTION VALUES (123,1,100,'C');
INSERT INTO WGB_TRANSACTION VALUES (123,1,50,'D');
INSERT INTO WGB_TRANSACTION VALUES (123,2,100,'C');
INSERT INTO WGB_TRANSACTION VALUES (456,1,50,'C');
INSERT INTO WGB_TRANSACTION VALUES (456,1,100,'C');
INSERT INTO WGB_TRANSACTION VALUES (456,3,100,'D');
INSERT INTO WGB_TRANSACTION VALUES (456,1,50,'C');
--The Query
WITH BALANCES AS (
SELECT CUSTOMER_NUMBER, ACCOUNT_TYPE,
SUM(DECODE(TRANSACTION_TYPE,'D',-1,'C',1,0)*TRANSACTION_AMOUNT) BALANCE
FROM WGB_TRANSACTION WHERE TRANSACTION_TYPE IN ('C','D')
GROUP BY ROLLUP ( CUSTOMER_NUMBER, ACCOUNT_TYPE )
)
SELECT C.FIRST_NAME, C.SURNAME, B.ACCOUNT_TYPE, TO_CHAR(B.BALANCE,'$9,999.99')
FROM BALANCES B LEFT JOIN WGB_CUSTOMER C ON C.CUSTOMER_NUMBER=B.CUSTOMER_NUMBER;
--RESULT
FIRST_NAME SURNAME ACCOUNT_TYPE TO_CHAR(B.BALANCE,'$9,999.99')
John Smith (null) $150.00
John Smith 2 $100.00
John Smith 1 $50.00
James Anderson (null) $100.00
James Anderson 3 -$100.00
James Anderson 1 $200.00
(null) (null) (null) $250.00