我有三张桌子,我需要计算2015年约翰史密斯的营业额除以月份。
OrderItems
------------ Orders
Products OrderItem_ID ------
---------- Order_ID <---> Order_ID
Product_ID <---> Product_ID Type
Name Quantity Date
Category UnitPrice Customer
表格通过Order_ID&amp; amp; Order_ID(选项卡OrderItems和Orders),然后按Product_IDs(选项卡Products和OrderItems)。我想我还是不需要制表产品。
Orders (Order_ID INT, Type INT, Date DATETIME, Customer VARCHAR)
OrderItems (OrderItem_ID INT, Order_ID INT, Product_ID INT, Quantity INT, UnitPrice MONEY)
Products (Product_ID INT, Name VARCHAR, Category VARCHAR)
由于我最后一次使用SQL已经有很长一段时间了,因此谷歌搜索和知识刷新了几十分钟和几十分钟。
我写了这个查询,但我完全不确定。你能来看看吗?
SELECT
SUM(a.quantity * a.price) AS 'turnover',
DATEPART(month, a.date) AS 'month'
FROM
(
SELECT
Quantity.OrderItems AS 'quantity',
UnitPrice.OrderItems AS 'price',
Date.Orders AS 'date',
Customer.Orders AS 'customer'
FROM Orders
JOIN Orders
ON OrderItems.Order_ID = Orders.Order_ID
WHERE
date BETWEEN 2015-01-01 and 2015-12-31
AND customer = 'John Smith'
) a
GROUP BY month
ORDER BY month
非常感谢
//纠正了代码中的一个小错误
答案 0 :(得分:0)
您需要将Orders
加入OrderItems
SELECT
SUM(a.quantity * a.price) AS 'turnover',
DATEPART(month, a.date) AS 'month'
FROM
(
SELECT
OI.Quantity AS 'quantity',
OI.UnitPrice AS 'price',
O.Date AS 'date',
O.Customer AS 'customer'
FROM Orders O
INNER JOIN OrderItems OI
ON O.Order_ID = OI.Order_ID
WHERE
O.date BETWEEN 2015-01-01 and 2015-12-31
AND O.customer = 'John Smith'
) a
GROUP BY DATEPART(month, a.date)
ORDER BY DATEPART(month, a.date)