SQL Server Management Studio一个月的销售总额

时间:2019-05-18 18:41:19

标签: sql-server

不知道我是否用规范化覆盖了它,但是有4个表:

  • 员工(ID,姓名)
  • 产品(ID,名称,价格)
  • Order_Details(ID,Employee_ID {FK},月,年)-购买时间和进行销售的员工
  • Order_Each_Product(订单ID {PK,FK},产品ID {PK,FK},数量)-购买了哪种产品以及购买了每种产品的数量

我想要这样的东西:

( Employee_Name, Month, Total_Sales_Made_In_That_Month_In_Dollar )

我认为您可以从2张桌子中获得每个订单的总和,例如:

SELECT SUM((Order_Each_Product.Quantity) * (Product.Price)) 
FROM Order_Each_Product 
INNER JOIN Product ON Order_Each_Product.ProductID = Product.ProductID
GROUP BY OrderID

但是您如何再次按员工将其分组并获得SUM的SUM?

2 个答案:

答案 0 :(得分:2)

在我编写代码时,Forpas击败了我!

SELECT
    Employee.Name, Year, Month, SUM(Quantity * Price) AS Total_Sales_In_Month
FROM 
    Order_Details

LEFT JOIN Employee
    ON (Order_Details.Employee_ID = Employee.ID)

LEFT JOIN Order_Each_Product
    ON (Order_Details.ID = Order_Each_Product.OrderID)

LEFT JOIN Product
    ON (Order_Each_Product.ProductID = Product.ID)

GROUP BY
    Employee.ID, Employee.Name, Year, Month

提示,您当前所称的Order_DetailsOrder_Each_Product通常分别称为order_headersorder_lines

答案 1 :(得分:1)

按员工的ID,姓名,年和月加入所有表和组:

select
  e.name,
  od.Year,
  od.Month,
  sum(oep.quantity * p.price) Total_Sales_Made_In_That_Month_In_Dollar
from employee e 
inner join order_details od on od.employee_id = e.id
inner join order_each_product oep on oep.orderid = od.id
inner join product p on p.id = oep.productid
group by e.id, e.name, od.Year, od.Month