我需要每个订单的订单项数量。
在此示例中,订单10为0,订单11为2行。
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)
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
SELECT
OrderDetailID,ItemID,OrderHeader.OrderHeaderID,CustID
FROM OrderDetail
JOIN OrderHeader
ON OrderDetail.OrderHeaderID=OrderHeader.OrderHeaderID
--
这是我需要帮助的地方 我需要COUNT(*)
FROM OrderDetail WHERE OrderDetail.OrderHeaderID=OrderHeader.OrderHeaderID
SELECT OrderHeader.OrderHeaderID,CustID,CountOfOrderDetail
FROM OrderHeader
JOIN OrderDetail
ON OrderDetail.OrderHeaderID=OrderHeader.OrderHeaderID
答案 0 :(得分:4)
select
ord.OrderHeaderID
, count(det.ItemID)
from
OrderHeader ord
left outer join
OrderDetail det
on
det.OrderHeaderID = ord.OrderHeaderID
group by
ord.OrderHeaderID
答案 1 :(得分:1)
SELECT OrderHeader.ID, count(OrderDetail.ID)
FROM OrderHeader
LEFT JOIN OrderDetail
ON OrderDetail.OrderHeaderID=OrderHeader.OrderHeaderID
GROUP BY OrderHeader.ID
答案 2 :(得分:1)
喜欢这个吗?
SELECT
h.OrderHeaderID,
h.CustID,
COUNT(d.OrderHeaderID) CountOfOrderDetail
FROM
OrderHeader h
LEFT JOIN OrderDetail d ON d.OrderHeaderID = h.OrderHeaderID
GROUP BY
h.OrderHeaderID,
h.CustID
答案 3 :(得分:0)