我的SQL server DB中有4个表:
OrderMaster (OrderId [primaryKey], Orderdate, TotalAmount, SupplierName)
OrderDetails (OrderDetailId[primaryKey], OrderId, Item_Id, Quantity, ManufacturerId)
ItemMaster (Item_Id [primaryKey], ITem Name, ITemCost)
ManufacturerMaster (ManuId[primaryKey], ManufacturerName, HandlingFees)
关系是:
Orderdetails表可以为ORderMaster表中的一条记录提供许多记录。
现在,我希望查询列出所有订单orderdate=05/01/2009
,其中以下项为列值:
如何按顺序执行命令?
答案 0 :(得分:1)
select OD.Id, count(IM.Item_Id), sum(IM.ItemCost * OD.ItemQuantity)
from OrderMaster OM
join OrderDetail OD on OD.OrderId = OD.OrderId
join ItemMaster IM on IM.Item_Id = OD.Item_Id
group by OD.OrderId
where OD.OrderDate >= '2009/05/01' and OD.OrderDate < '2009/05/02'
根据新要求更新
答案 1 :(得分:0)
像这样的东西
SELECT
OrderMaster.OrderId,
COUNT(OrderDetailId) as TotalUniqeItems,
SUM(Quantity) as TotalItems,
SUM(ItemCost) as CostofUniqueItems,
(
SELECT ItemCost * Quantity
FROM OrderDetail od
JOIN ItemMaster im ON im.Item_Id = od.Item_Id
WHERE od.Order_Id = OrderMaster.OrderId
) as TotalCost
FROM OrderMaster
JOIN OrderDetail ON OrderMaster.OrderId = OrderDetail.OrderId
JOIN ItemMaster ON ItemMaster.Item_Id = OrderDetail.Item_Id
WHERE OrderDate >= '2009/05/01' AND OrderDate <= '2009/05/02'
由于我不确定所需的确切结果,因此我提供了2种不同的方式来获取项目的总资产和成本。
注意,我没有检查我的语法,但这应该很接近。