我有两个表:Order和Order_Item。
订单有列:
1)Order_Id整数
2)Order_Time日期
Order_Item 有列:
1)Order_Item_Id整数
2)Order_Id整数(FK)
3)Order_Quantity整数
4)Product_Id(FK)//来自产品表(Product_Id,Product_Name,Product_Price)
我想写一个这样的查询:
SELECT Product_Id,COUNT(Product_Id)* Order_Quantity
FROM Order_Item,订单
WHERE Order.Date BETWEEN '31 -dec-2015'和 '5-jan-2016'
AND Order_Item.Order_Id = Order.Order_Id
GROUP BY OrderItem.Product_Id;
结果应如下:
PRODUCT_ID Number_of_orders_from_customers
1 23
2 45
我找到了很多解决方案(比如这个Efficiently Include Column not in Group By of SQL Query),但问题是我使用GROUP BY查询Order_Quantity。
任何解决方案?
答案 0 :(得分:0)
SELECT Product_Id , COUNT(*) AS Number_of_orders_from_customers
FROM Order_Item, Order
WHERE Order.Date BETWEEN '31-dec-2015' and '5-jan-2016'
AND Order_Item.Order_Id =Order.Order_Id
GROUP BY OrderItem.Product_Id ;
答案 1 :(得分:0)
我认为您需要sum
,以及正确的连接语法,表别名和标准日期格式:
SELECT oi.Product_Id , SUM(oi.Order_Quantity)
FROM Order_Item oi JOIN
`Order` o
ON oi.Order_Id = o.Order_Id
WHERE o.OrderTime BETWEEN '2015-12-31' and '2015-01-05'
GROUP BY oi.Product_Id ;