简体   繁体   English

计算特定月份mysql的平均支出(支出/人)

[英]Calculating average spending (amount spent/person) in a particular month mysql

I have three tables in my database with schema: 我的数据库中具有架构的三个表:

items (itemID: integer, description: string, price: integer)
orders (orderID: integer, itemID: integer, aID: integer, customerID: integer, date: date)
customers (customerID: integer, fName: string, lName: string)

I need to calculate the average amount of money spent by ALL customers in a given month (between 2013-03-01 and 2013-03-31) which is total amount spent/total no of customers, to do this I need to calculate the sum of the prices of all products purchased between those dates (using information from itemID in orders and price in items), I did this with this code: 我需要计算给定月份(2013年3月1日至2013年3月31日之间)所有客户的平均支出金额,即支出的总金额/客户总数,为此,我需要计算在这些日期之间购买的所有产品的价格总和(使用订单中itemID中的信息和商品中价格的信息),我使用以下代码执行此操作:

SELECT SUM(price) FROM items WHERE itemID IN( SELECT itemID FROM orders WHERE date BETWEEN '2013-03-01' AND '2013-03-31' )

But i am having trouble figuring out how to divide this number by total number of customers (which can be found by counting the number of customers on the customers table - the unique key is the customerID) 但是我很难弄清楚如何将这个数字除以客户总数(可以通过计算客户表上的客户数量来找到-唯一键是customerID)

Can anyone help? 有人可以帮忙吗? thanks! 谢谢!

You can use a subquery : 您可以使用子查询:

SELECT SUM(i.price)/(SELECT COUNT(*) FROM customers)
FROM items i
LEFT JOIN orders o ON i.itemID = o.itemID
                  AND o.date BETWEEN '2013-03-01' AND '2013-03-31'
WHERE o.itemID IS NOT NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM