sql - 根据SQL Server中的配置表生成汇总数据

标签 sql sql-server-2008 tsql summary

我正在尝试从 SQL Server 2008 中的分数列表生成摘要。
我有两张 table :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 词干来实现这一点,但它会将摘要生成为列。我可能需要旋转它或从多个选择语句中使用 UNION。但是,如果向 ScoreMinMax 中添加了新行,这种方法似乎不可扩展。 table 。
到目前为止,我能够使用 CROSS JOINT 获得类似于上面示例的一些结果,但它并不总是产生正确的结果。

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

SQL Fiddle link
ScorePerson - contains actual scores

Table screenshot
ScoreMinMax - the configuration for min and max score bands

enter image description here

最佳答案

您可以使用聚合函数:

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/

相关文章:

java - Tapestry/JDBC - 存储日期

mysql - 如何使用 Outer Join 和 Group By 在查询中包含 NULL 值

sql - hive sql 聚合

sql-server-2008 - 导入CSV文件时如何删除文本周围的双引号?

sql - MERGE 违反 PRIMARY KEY 约束

PHP-MySQL | PHP-MySQL那么更好/更干净的方式吗?

sql - 在 SQL Server 2008 中查找有错误的存储过程?

sql-server - 删除聚集索引会从列中删除 PK

c# - 我如何在 SQL 中使用枚举而不在我的 SQL 脚本/过程中硬编码魔数(Magic Number)?

sql - 表列之间的一对多关系。分组和查找组合