I need to find the average amount of money spent by country, using the two tables below in oracle. Sale_total is the money spent in each sale and Cust_country is the customer's country. Any help would be greatly appreciated.

Tables

Sale

Sale_Id
Payment_ID
Ship_Id
Customer_ID
Sale_total ==> Money Spent
Sale_date
Sale_time

Customer

Cust_name
Cust_address
Cust_city
Cust_country
Cust_phone
Cust_age
Cust_sex
有帮助吗?

解决方案

You need to have a link between the Sale and Customer tables. Presumably place Customer_ID in the Customer table as a primary key, and have Customer_ID in the Sale table be a foreign key. Assuming you do that, you can then run the below query.

SELECT
AVG(S.Sale_Total) Spent,
c.Cust_country
FROM
Sale S
INNER JOIN
Customer C on S.Customer_ID=C.Customer_ID
GROUP BY C.Cust_Country

This tells you the average amount spent, and the country where it was spent.

The key to understanding this answer is that AVG (the average function) is an aggregate function, as it combines things. Often when you have an aggregate function, you have to group the other columns, hence why we included the GROUP BY clause.

The reason you need Customer Id in the Customer table (apart from being the logical place for it) is so that you can establish a relationship between the Customer and Sale tables.

Another way to establish the relation is you can create a new table to link Customer and Sale together. Call it Customer Sales. For example:

Customer_Sales

Customer_Id
Sale_Id

Then you'd adjust the query to join based on that.

其他提示

Try this:

SELECT C.Cust_country as Country, AVG(S.Sale_total) as Spent
FROM Sale S INNER JOIN
Customer C on S.Customer_ID=C.Customer_ID
GROUP BY C.Cust_country

AVG is an aggregate function that evaluates the average of an expression over a set of rows.

Read more about here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top