如何使用WITH ROLLUP结果确定百分比

时间:2012-05-19 23:56:28

标签: tsql

我正在尝试使用With Rollup函数来确定查询中返回的TOTAL行数,并使用该数字来确定每个结果相对于查询中TOTAL行的百分比。 这是我的代码:

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,但无法弄清楚如何计算查询中的百分比。

由于 安迪

1 个答案:

答案 0 :(得分: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');