如何在同一查询中使用Count和Sum?

时间:2012-05-10 11:20:11

标签: sql-server sql-server-2008 count sum aggregate

我使用聚合函数“SUM”编写了以下查询。

SELECT 
       D.PODetailID, 
       SUM(D.AcceptedQty) 
FROM STR_MRVDetail D 
INNER JOIN STR_MRVHeader H ON H.MRVID = D.MRVID 
INNER JOIN PUR_POHeader PH ON PH.POID = H.POID 
INNER JOIN PUR_PODetail PD ON PD.PODetailID = D.PODetailID
WHERE H.StatusID = 4
AND PH.POID = 839
AND (SELECT 
           SUM(AcceptedQty) 
     FROM 
           STR_MRVDetail 
     WHERE 
           STR_MRVDetail.PODetailID = PD.PODetailID) = 
                              (SELECT POQuantity FROM PUR_PODetail 
                               WHERE PUR_PODetail.PODetailID = PD.PODetailID)
                               GROUP BY D.PODetailID

目前此查询返回2行。我想检索此查询的计数。如何计算上述查询的行?

2 个答案:

答案 0 :(得分:2)

SELECT COUNT(*) as Total_Rows
FROM
(
SELECT D.PODetailID as PODetailID, SUM(D.AcceptedQty) as Total_AcceptedQty
FROM STR_MRVDetail D 
INNER JOIN STR_MRVHeader H ON H.MRVID = D.MRVID 
INNER JOIN PUR_POHeader PH ON PH.POID = H.POID 
INNER JOIN PUR_PODetail PD ON PD.PODetailID = D.PODetailID
WHERE H.StatusID = 4
AND PH.POID = 839
AND (SELECT SUM(AcceptedQty) FROM STR_MRVDetail 
     WHERE STR_MRVDetail.PODetailID = PD.PODetailID) = 
     (SELECT POQuantity FROM PUR_PODetail 
      WHERE PUR_PODetail.PODetailID = PD.PODetailID)
GROUP BY D.PODetailID
) as t

答案 1 :(得分:2)

您可以将@@ROWCOUNT添加到查询中,该查询还会为您提供最终结果集以及结果集中所有行的计数。

SELECT D.PODetailID, SUM(D.AcceptedQty), @@ROWCOUNT FROM STR_MRVDetail D  
INNER JOIN STR_MRVHeader H ON H.MRVID = D.MRVID  
INNER JOIN PUR_POHeader PH ON PH.POID = H.POID  
INNER JOIN PUR_PODetail PD ON PD.PODetailID = D.PODetailID 
WHERE H.StatusID = 4 
AND PH.POID = 839 
AND (SELECT SUM(AcceptedQty) FROM STR_MRVDetail  
     WHERE STR_MRVDetail.PODetailID = PD.PODetailID) =  
     (SELECT POQuantity FROM PUR_PODetail  
      WHERE PUR_PODetail.PODetailID = PD.PODetailID) 
GROUP BY D.PODetailID