来自子查询的OrderHeader。*,COUNT(OrderDetail)

时间:2009-05-21 19:52:38

标签: sql-server subquery

之前的问题是关于获取OrderID和关联订单项的数量。 现在我想得到OrderHeader行中的其余字段。

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
    */

3 个答案:

答案 0 :(得分:3)

SELECT
    OrderHeader.*, 
    OrderDetailCount.CountOfOrderDetail
FROM OrderHeader
JOIN (
    SELECT 
       OH.OrderHeaderId,
       COUNT(OD.OrderHeaderID) AS CountOfOrderDetail    
    FROM OrderHeader OH    
    LEFT JOIN OrderDetail OD ON 
       OD.OrderHeaderID = OH.OrderHeaderID    
    GROUP BY OH.OrderHeaderID
) as OrderDetailCount ON
    OrderHeader.OrderHeaderId = OrderDetailCount.OrderHeaderId

答案 1 :(得分:0)

怎么样:

select oh.*, (
    select count(*) 
    from OrderDetail 
    where OrderHeaderID = oh.OrderHeaderID) as CountOfOrderDetail
from OrderHeader oh

答案 2 :(得分:0)

SELECT h.OrderHeaderID,
        h.CustID,
        h.OrderDate,
        h.OrderTypeID,
        h.OrderGroupID,
        h.OrderCatID,
        COUNT(*) 
FROM OrderHeader h 
JOIN OrderDetail d ON h.OrderHeaderId = d.OrderHeaderId 
GROUP BY h.OrderHeaderID,
        h.CustID,
        h.OrderDate,
        h.OrderTypeID,
        h.OrderGroupID,
        h.OrderCatID