0

我正在尝试使用 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 但无法弄清楚如何计算查询中的百分比的记录中的总数。

谢谢安迪

4

1 回答 1

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');
于 2012-05-20T14:39:22.683 回答