MySQL:根据State求客户的平均余额

MySQL: Find the average balance of customers based on State

根据状态求客户的平均余额

select * from Customer_info;
select * from Account_info;

select Customer_info.Customer_ID, Customer_info.State, Account_info.Balance, Account_info.Customer_ID
from Customer_info
inner join Account_info on Customer_info.Customer_ID = Account_info.Customer_ID;

select Customer_info.Customer_ID, Customer_info.State, avg(Balance) as Average_Bal
from Customer_info
inner join Account_info on Customer_info.Customer_ID = Account_info.Customer_ID
group by State;

卡住了,可以使用一些 help/suggestions。

你似乎想要:

select c.state, avg(a.balance) as average_bal
from customer_info c
inner join account_info a on a.customer_id = c.customer_id
group by c.state;

select子句需要与group by子句保持一致:所有非聚合列都必须出现在group by子句中。

请注意,我添加了 table 别名,这缩短了查询。我还为列 balance 添加了它所属的 table 前缀,因此查询是明确的(我假设 account_info)。