tags:

views:

444

answers:

2

I have 4 Tables in my SQL server DB . OrderMaster,OrderDetails,ItemMaster,ManufacturerMaster

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)

The Relations are OrderDetails table Order id is refering the primary key of OrderMAster table(one to many) OrderDetails table Item_Id is refering the primary key of ItemMaster ManufacturerIdtable Order id is refering the primary key of ManufacturerMaster

Orderdetails table can have many records for one record in ORderMaster table.

Now i want to have a Query to List all Orders which;s orderdate=05/01/2009 with the below Items as columns values

1 . Order number
2 . Total Number of Items (number of child records in orderdetail table) for each order
3 . Total (Sum of )ITemcost for all the items in an order.

How to do the Order by ??

+1  A: 
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'

updated per new requirements

Rob Elliott
I need to have the Sum as (Item Cost*Order Quantity).Each order details record has a column to store Quanity
Shyju
A: 

Something like this

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'

I included 2 different ways to get Total Numnber of Items and the cost since I was unsure of the exact desired result.

Note, I did not check my syntax, but this should be close.

palehorse