我正在尝试从 SQL Server 2008 中的分数列表生成摘要。
我有两张 table :SQL Fiddle linkScorePerson
表包含人们的 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 词干来实现这一点,但它会将摘要生成为列。我可能需要旋转它或从多个选择语句中使用 UNION。但是,如果向
ScoreMinMax
中添加了新行,这种方法似乎不可扩展。 table 。到目前为止,我能够使用 CROSS JOINT 获得类似于上面示例的一些结果,但它并不总是产生正确的结果。
有没有人能够指出我如何实现这一目标的正确方向?
SQL Fiddle link
ScorePerson - contains actual scores
ScoreMinMax - the configuration for min and max score bands
最佳答案
您可以使用聚合函数:
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
关于sql - 根据SQL Server中的配置表生成汇总数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12601708/