基于SQL Server中的配置表生成摘要数据
我正在尝试从SQLServer2008中的分数列表生成摘要。 我有两张桌子: ScorePerson表包含人员ID和他们在-5到15之间的分数。SQL/存储过程的最终用户需要创建如下摘要:基于SQL Server中的配置表生成摘要数据,sql,sql-server-2008,tsql,summary,Sql,Sql Server 2008,Tsql,Summary,我正在尝试从SQLServer2008中的分数列表生成摘要。 我有两张桌子: ScorePerson表包含人员ID和他们在-5到15之间的分数。SQL/存储过程的最终用户需要创建如下摘要: Scoreband| TotalNoOfPeople | AvgScore -------------------------------- -5 to 0 | 2 | -2 0 to 5 | 3 | 2 5 to 10 | 2
Scoreband| TotalNoOfPeople | AvgScore
--------------------------------
-5 to 0 | 2 | -2
0 to 5 | 3 | 2
5 to 10 | 2 | 8
10 to 15 | 3 | 13.3
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
最终用户应可从ScoreMinMax表中配置分数带,即最小值和最大值
我已经尝试使用CASE语句来实现这一点,但它会以列的形式生成摘要。我可能需要从多个select语句中透视它或使用UNION。但是,如果ScoreMinMax表中添加了新行,这种方法似乎不可伸缩。
到目前为止,我能够使用CROSS JOINT获得一些类似于上面示例的结果,但它并不总是产生正确的结果
有没有人能为我指出正确的方向来实现这一目标
试一试
请注意,我只在其中一组中包含了边界0,5,10的分数 您可以使用聚合函数:
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)
看见
如果您在现有范围内没有人员,您可以向我们介绍如下内容:
Scoreband| TotalNoOfPeople | AvgScore
--------------------------------
-5 to 0 | 2 | -2
0 to 5 | 3 | 2
5 to 10 | 2 | 8
10 to 15 | 3 | 13.3
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
看见
编辑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;
请参阅是否需要一个查询,该查询将仅从ScorePerson中选择一个类似于表ScoreMinMax的结果集?如何处理重叠值0,5,10?你可以得到最低和最高的分数,比如-5比0,1比5,6比10等等,或者按照波迪卢斯卡的建议去做。太好了,谢谢。如果没有人在给定的分数范围内。有没有可能在0个TotalNoPeople的情况下仍然输出该波段,而不是完全不显示该波段?@Sivakanesh看到下面我的答案就可以了。对不起,我的意思是,如果说分数带“-5到0”中没有任何一个。与其不显示波段,不如说“5到0”的-count是0@Sivakanesh ok,但如果分数超出表中的范围,是否要显示任何内容?否,在本例中不需要显示。
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;
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