根据SQL Server中的配置表生成摘要数据

时间:2012-09-26 12:26:55

标签: sql sql-server-2008 tsql summary

我正在尝试从SQL Server 2008中的分数列表生成摘要 我有两张桌子:SQL Fiddle link

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来实现这一点,但它会将摘要生成为列。我可能需要透视它或从多个select语句中使用UNION。但是,如果在ScoreMinMax表中添加了新行,则此方法似乎不可扩展。 到目前为止,我能够使用CROSS JOINT获得类似于上面示例的一些结果,但它并不总能产生正确的结果。

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

SQL Fiddle link

ScorePerson - contains actual scores

Table screenshot

ScoreMinMax - the configuration for min and max score bands

enter image description here

3 个答案:

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

答案 1 :(得分: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)中包含了分数。

答案 2 :(得分: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