Subselect和Max

时间:2012-02-20 19:11:03

标签: tsql sql-server-2008-r2

好吧,我一直试图将这个概念化为下午更好的部分,但仍然无法弄清楚如何构建这个子选择。

我需要报告的数据是按过去3个财政年度分组的特定学生专业的年龄。每个财政年度有3个学期(夏季,秋季,春季)。我需要将我的查询分组到fiscalyear和agerange字段,然后计算不同的学生ID。

我目前在我的SQL语句中有这个:

Select COUNT(distinct StuID), AgeRange, FiscalYear

from tblStatic

where Campus like 'World%' and (enrl_act like 'REG%' or enrl_act like 'SCH%') 
    and StuMaj = 'LAWSC' and FiscalYear IN ('09/10', '10/11', '11/12')

group by FiscalYear, AgeRange

order by FiscalYear, AgeRange

所以这一切都很好而且花花公子,除非它与我的学生人数不匹配。原因是,人们可能会在财政年度期间跨越年龄范围并将其加入我的计数两次。

如何使用子选择来解决此重复条目?我一直努力工作的领域是我的学期领域,并使用max来找到特定学生的fiscalyear期间的最大学期。

数据样本:

Count   AgeRange            FiscalYear
3           1 to 19             09/10
20          20 to 23            09/10
60          24 to 29            09/10
96          30 to 39            09/10
34          40 to 49            09/10
14          50 to 59            09/10
3           60+                 09/10
2           1 to 19             10/11
24          20 to 23            10/11
73          24 to 29            10/11
109         30 to 39            10/11
43          40 to 49            10/11
11          50 to 59            10/11
2           60+                 10/11
1           1 to 19             11/12
17          20 to 23            11/12
75          24 to 29            11/12
123         30 to 39            11/12
44          40 to 49            11/12
14          50 to 59            11/12
2           60+                 11/12

解决方案:(刚刚开始工作并制作了符合他们想象的人数)

Select COUNT(distinct S.StuID), AR.AgeRange, S.FiscalYear
from tblStatic S
INNER JOIN
(   Select S.StuID, MIN(AgeRange) as AgeRange
    From tblStatic S
    Group By S.StuID) AR on S.StuID=AR.StuID

where Campus like 'World%' and (enrl_act like 'REG%' or 
enrl_act like 'SCH%')
and StuMaj = 'LAWSC' and FiscalYear IN ('09/10', '10/11', '11/12') 
group by S.FiscalYear, AR.AgeRange
order by S.FiscalYear, AR.AgeRange

1 个答案:

答案 0 :(得分:0)

将每个学生的年龄范围替换为该会计年度的最大年龄(或最小,如果您愿意),然后计算它们:

;
WITH sourceData AS (
  SELECT
    StudID,
    MaxAgeRangeThisFiscalYear = MAX(AgeRange) OVER
                                (PARTITION BY StudID, FiscalYear),
    FiscalYear
  FROM tblStatic
  WHERE Campus LIKE 'World%'
    AND (enrl_act LIKE 'REG%' OR enrl_act LIKE 'SCH%') 
    AND StuMaj = 'LAWSC'
    AND FiscalYear IN ('09/10', '10/11', '11/12')
)
SELECT
  FiscalYear,
  AgeRange = MaxAgeRangeThisFiscalYear,
  Count    = COUNT(DISTINCT StudID)
FROM sourceData
GROUP BY
  FiscalYear,
  MaxAgeRangeThisFiscalYear
ORDER BY
  FiscalYear,
  MaxAgeRangeThisFiscalYear