在子查询中计数(*)

时间:2009-05-21 18:37:33

标签: sql-server subquery

我需要每个订单的订单项数量。

在此示例中,订单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

4 个答案:

答案 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)

为了将来参考,您需要避免使用以下内容:

SELECT COUNT(*)
FROM OrderDetail
GROUP BY OrderHeaderID

乍一看似乎简单而优雅,但请注意,您将错过OrderHeader表中没有订单的任何订单。如果表示它们很重要(计数为0),请参阅TomalakAutocracy的答案herehere

感谢KM指出这一点! (见下面的评论)