An earlier question was answered about getting the OrderID and the number of associated line items. Now I would like to get the rest of the fields in the OrderHeader row.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.OrderDetail') AND type in (N'U'))
DROP TABLE OrderDetail
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.OrderHeader') AND type in (N'U'))
DROP Table OrderHeader
GO
CREATE TABLE OrderHeader(
OrderHeaderID Int Primary Key Identity(10,1),
CustID Int,
OrderDate DateTime default getdate(),
OrderTypeID Int default 0, -- References OrderType
OrderGroupID Int Default 0, -- References OrderGroup
OrderCatID Int Default 0 -- References OrderCat
)
GO
CREATE TABLE OrderDetail(
OrderDetailID Int Primary Key Identity(100,1),
OrderHeaderID Int REFERENCES OrderHeader,
ItemID Int)
GO
DECLARE @OrderHeaderID Int
INSERT INTO OrderHeader(CustID) VALUES(1000)
INSERT INTO OrderHeader(CustID) VALUES(1001)
SET @OrderHeaderID=SCOPE_IDENTITY()
INSERT INTO OrderDetail(OrderHeaderID,ItemID) VALUES(@OrderHeaderID,3)
INSERT INTO OrderDetail(OrderHeaderID,ItemID) VALUES(@OrderHeaderID,4)
GO
-- This query gives me the number of line items per order
SELECT OH.OrderHeaderID,COUNT(OD.OrderHeaderID) AS CountOfOrderDetail
FROM OrderHeader OH
LEFT JOIN OrderDetail OD
ON OD.OrderHeaderID = OH.OrderHeaderID
GROUP BY OH.OrderHeaderID
/*
This is where I need help
I would like a query to show
SELECT OrderHeader.*,CountOfOrderDetail
*/