My requirement is to display country name, total number of invoices and their average amount. Moreover, I need to return only those countries where the average invoice amount is greater than the average invoice amount of all invoices.
Query for Oracle Database
SELECT cntry.NAME, COUNT(inv.NUMBER), AVG(inv.TOTAL_PRICE) FROM COUNTRY cntry JOIN CITY ct ON ct.COUNTRY_ID = cntry.ID JOIN CUSTOMER cst ON cst.CITY_ID = ct.ID JOIN INVOICE inv ON inv.CUSTOMER_ID = cst.ID GROUP BY cntry.NAME, inv.NUMBER, inv.TOTAL_PRICE HAVING AVG(inv.TOTAL_PRICE) > (SELECT AVG(TOTAL_PRICE) FROM INVOICE);
Result: Austria 1 9500
Expected: Austria 2 4825
Schema
Country
ID(INT)(PK) | NAME(VARCHAR)
City
ID(INT)(PK) | NAME(VARCHAR) | POSTAL_CODE(VARCHAR) | COUNTRY_ID(INT)(FK)
Customer
ID(INT)(PK) | NAME(VARCHAR) | CITY_ID(INT)(FK) | ADDRS(VARCHAR) | POC(VARCHAR) | EMAIL(VARCHAR) | IS_ACTV(INT)(0/1)
Invoice
ID(INT)(PK) | NUMBER(VARCHAR) | CUSTOMER_ID(INT)(FK) | USER_ACC_ID(INT) | TOTAL_PRICE(INT)
Advertisement
Answer
With no sample data, we can’t really tell whether this:
Expected: Austria 2 4825
is true or not.
Anyway: would changing the GROUP BY
clause to
GROUP BY cntry.NAME
(i.e. removing additional two columns from it) do any good?