4

我正在尝试从 SQL Server 2008 中的分数列表生成摘要。
我有两个表:SQL Fiddle 链接

ScorePerson表包含人员的 ID 和他们从 -5 到 15 的分数。我的 SQL/存储过程的最终用户需要创建如下摘要:

Scoreband| TotalNoOfPeople | AvgScore
--------------------------------
-5 to 0  | 2               | -2
0 to 5   | 3               |  2
5 to 10  | 2               |  8
10 to 15 | 3               | 13.3

ScoreMinMax最终用户应该可以从表格中配置得分带,即最小值和最大值。

我曾尝试使用 CASE stement 来实现这一点,但它会将摘要生成为列。II 可能需要旋转它或从多个选择语句中使用 UNION。ScoreMinMax但是,如果向表中添加了新行,这种方法似乎无法扩展。到目前为止,我能够使用 CROSS JOINT 获得类似于上面示例的一些结果,但它并不总是产生正确的结果。

有人能指出我如何实现这一目标的正确方向吗?

SQL 小提琴链接

ScorePerson - contains actual scores

表格截图

ScoreMinMax - the configuration for min and max score bands

在此处输入图像描述

4

3 回答 3

4

您可以使用聚合函数:

select title ScoreBand,
  count(*) TotalNoPeople, 
  avg(p.score) AvgScore  
from scoreperson p
inner join scoreminmax m
  on p.score between m.minscore and m.maxscore
group by Title
order by cast(left(title, 2) as int) 

SQL Fiddle with Demo

如果您在现有范围内没有人,您可以使用以下方法:

select case when title is not null 
            then title
            else 'No Range' end ScoreBand,
  count(personid) TotalNoPeople, 
  avg(p.score) AvgScore  
from scoreperson p
left join scoreminmax m
  on p.score between m.minscore and m.maxscore
group by id, Title
order by id

SQL Fiddle with Demo

编辑#2,根据您可以使用的评论:

select m.title ScoreBand,
  count(p.personid) TotalNoPeople, 
  avg(p.score) AvgScore  
from scoreminmax m
left join scoreperson p
  on p.score between m.minscore and m.maxscore
group by m.id, m.Title
order by m.id;

SQL Fiddle with Demo

于 2012-09-26T12:33:12.550 回答
1

尝试

Select Title, count(personid), AVG(score)
from 
    scoreminmax  
    left join scoreperson 
    on scoreperson.score>=minscore 
    and scoreperson.score<maxscore 
group by ID,title 
order by ID 

请注意,我仅在其中一组中包含了边界(0,5,10)的分数。

于 2012-09-26T12:32:42.090 回答
0
select smm.Title Scoreband, count(*) TotalNoOfPeople, avg(sp.Score) AvgScore
from 
    ScorePerson sp
    inner join
    ScoreMinMax smm on sp.Score >= smm.MinScore and sp.Score < smm.MaxScore
group by smm.Title
于 2012-09-26T12:36:01.327 回答