While the rest of the code is functional, I can't figure out how to average the "Total Purchases" using the "Number of Purchases" to find the "Average Purchase Amount".
--- Query ---
SELECT C.CUS_CODE,
C.CUS_BALANCE,
ROUND(SUM(L.LINE_UNITS * L.LINE_PRICE), 2) AS "Total Purchases",
COUNT(L.LINE_NUMBER) AS "Number of Purchases",
AVG("Total Purchases") as "Average Purchase Amount"
FROM CUSTOMER AS C
RIGHT JOIN INVOICE AS I
ON C.CUS_CODE = I.CUS_CODE
RIGHT JOIN LINE AS L
ON I.INV_NUMBER = L.INV_NUMBER
WHERE L.INV_NUMBER = I.INV_NUMBER
GROUP BY CUS_CODE, "Number of Purchases"
I've tried using the AVG() function with "Total Purchases" and grouping by "Number of Purchases" alias's but the query returns a 0 in each "Average Purchase Amount" column.
The output should represent the following:
SELECT CUS_CODE, CUS_BALANCE,
Total AS "Total Purchases",
Number as "Number of Purchases",
ROUND((Total/Number),2) as "Average Purchase Amount"
FROM (SELECT C.CUS_CODE,
C.CUS_BALANCE,
ROUND(SUM(L.LINE_UNITS*L.LINE_PRICE),2) AS Total,
COUNT(L.LINE_NUMBER) AS Number
FROM CUSTOMER AS C
RIGHT JOIN INVOICE AS I
ON C.CUS_CODE = I.CUS_CODE
RIGHT JOIN LINE AS L
ON I.INV_NUMBER = L.INV_NUMBER
WHERE L.INV_NUMBER = I.INV_NUMBER
GROUP BY CUS_CODE, "Total Purchases"
) AS A