[英]SQL: How to use DISTINCT on a foreign key without using it in an aggregate function
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. 但是,当我将
DISTINCT sales.customerid
放进去时,它希望我将其放到一个聚合函数中,但是当我这样做时,它将平均值分开。 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
您可以使用
group by
而不是DISTINCT
By the Way, INNER JOIN
is better than CROSS JOIN
on this case. 顺便说一下,在这种情况下,
INNER JOIN
比CROSS JOIN
更好。
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. 使用GROUP BY子句代替Distinct,这会将所有重复的客户分组。
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. 但是请记住,SELECT中所有不在聚合函数中的属性都应存在于GROUP BY子句中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.