2012-05-19 122 views
0

我試圖使用With Rollup函數來確定在我的查詢中返回的總的行數,並使用該數字來確定每個結果相對於TOTAL的百分比查詢中的行。 這裏是我的代碼:如何在確定百分比時使用WITH ROLLUP結果

Declare @startDate DateTime, @endDate DateTime; 
Set @startDate = '01/01/01' 
Set @endDate = '01/01/13' 

SELECT 
    isnull(EducationType.EducationTypeDesc, 'UNKNOWN') as 'Education Type Description', 
    COUNT(isnull(EducationType.EducationTypeDesc, 'UNKNOWN')) as 'Record Count' 
FROM 
    EducationType LEFT OUTER JOIN 
    Education ON EducationType.EducationTypeID = Education.EducationTypeID LEFT OUTER JOIN 
    Volunteer ON Volunteer.PartyID = Education.PartyID 
WHERE  (Volunteer.SwornDate BETWEEN @startDate AND @endDate) 
GROUP BY isnull(EducationType.EducationTypeDesc, 'UNKNOWN') 
WITH ROLLUP 
ORDER BY isnull(EducationType.EducationTypeDesc, 'UNKNOWN') 

我得到的總數在其中EducationType.EducationTypeDesc顯示NULL,但無法弄清楚如何計算在查詢中的百分比記錄。

感謝 安迪

回答

0

加載行從查詢中的非分組版本數,並計算百分比:

Declare @startDate DateTime, @endDate DateTime; 
Set @startDate = '01/01/01'; 
Set @endDate = '01/01/13'; 
DECLARE @rows MONEY; 

SELECT @rows=COUNT(1) 
FROM 
    EducationType LEFT OUTER JOIN 
    Education ON EducationType.EducationTypeID = Education.EducationTypeID LEFT OUTER JOIN 
    Volunteer ON Volunteer.PartyID = Education.PartyID 
WHERE  (Volunteer.SwornDate BETWEEN @startDate AND @endDate); 

SELECT 
    isnull(EducationType.EducationTypeDesc, 'UNKNOWN') as 'Education Type Description', 
    COUNT(isnull(EducationType.EducationTypeDesc, 'UNKNOWN')) as 'Record Count', 
    COUNT(isnull(EducationType.EducationTypeDesc, 'UNKNOWN'))/@rows * 100 as 'Percent' 
FROM 
    EducationType LEFT OUTER JOIN 
    Education ON EducationType.EducationTypeID = Education.EducationTypeID LEFT OUTER JOIN 
    Volunteer ON Volunteer.PartyID = Education.PartyID 
WHERE  (Volunteer.SwornDate BETWEEN @startDate AND @endDate) 
GROUP BY isnull(EducationType.EducationTypeDesc, 'UNKNOWN') 
WITH ROLLUP 
ORDER BY isnull(EducationType.EducationTypeDesc, 'UNKNOWN'); 
+0

非常感謝你回答。它像一個魅力。 Andy –

+1

不客氣,覺得通過回答檢查Accepted複選框:) –