So I want to find the average amount everyone who purchased flowers, earns. However, I need to account for duplicates, because some people may have purchased flowers multiple times, and that would mess up the average.
But when I put DISTINCT sales.customerid
it wants me to put it in an aggregate function, but when I do that, it separates the averages. It doesn't put it into one average.
SELECT DISTINCT sales.customerid, AVG(moneyearned) AS averageearned
FROM customer, sales
WHERE customer.customerid = sales.customerid
AND (purchaseflower = TRUE);
What am I doing wrong?
You might use group by
instead of DISTINCT
By the Way, INNER JOIN
is better than CROSS JOIN
on this case.
SELECT customer.CustomerID, AVG(moneyearned) AS averageearned
FROM customer INNER JOIN sales
ON customer.CustomerID = sales.customerid
WHERE purchaseflower = TRUE
GROUP BY customer.CustomerID;
Use GROUP BY clause instead of Distinct this will group all duplicate customers.
SELECT sales.customerid, AVG(moneyearned) AS averageearned
FROM customer, sales
WHERE customer.customerid = sales.customerid
AND (purchaseflower = TRUE)
GROUP BY sales.customerid;
But remember all attributes in SELECT which are not in aggregated function should be present inside GROUP BY clause.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.