gpt4 book ai didi

mysql - SQL:如何在外键上使用 DISTINCT 而不在聚合函数中使用它

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:47 25 4
gpt4 key购买 nike

所以我想找出每个购买鲜花的人的平均收入。但是,我需要考虑重复的情况,因为有些人可能多次购买鲜花,这会弄乱平均值。

但是当我输入 DISTINCT sales.customerid 时,它希望我将它放在一个聚合函数中,但是当我这样做时,它会将平均值分开。它没有把它归为一个平均值。

SELECT DISTINCT sales.customerid, AVG(moneyearned) AS averageearned
FROM customer, sales
WHERE customer.customerid = sales.customerid
AND (purchaseflower = TRUE);

我做错了什么?

最佳答案

您可以使用 group by 而不是 DISTINCT

顺便说一下,在这种情况下,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;

SQLFiddle

关于mysql - SQL:如何在外键上使用 DISTINCT 而不在聚合函数中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48699112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com