--分数段分布
DECLARE @levels VARCHAR(100) = '10,20,30,40,50,60,70,80,90,100'; --自定义分数段
DECLARE @paperId VARCHAR(100)='0000000000001019'--试卷编号
WITH tbTemp AS (--处理分数段SELECT L.levelFROM (SELECT [value] = CONVERT(XML, '<v>' + REPLACE(@levels, ',', '</v><v>') + '</v>')) TOUTER APPLY (SELECT LEVEL = CONVERT(INT, N.v.value('.', 'varchar(100)'))FROM T.[value].nodes('/v') N(v)) L), tbLevel AS (--生成分数段区间SELECT (SELECT ISNULL(MAX(t.level), 0)FROM tbTemp AS tWHERE t.LEVEL < tt.level) AS level0,tt.level AS level1FROM tbTemp AS tt),tbScore AS(--处理成绩为null或0分,为了分配到0-?区间SELECT (CASE WHEN tp.GetScore > 0 THEN tp.GetScore ELSE 0.1 END) AS pScoreFROM 成绩表 AS tpWHERE tp.PaperID = @paperId)
--统计区间人次
SELECT tl.level0,tl.level1,(SELECT COUNT(0)FROM tbScore AS tsWHERE ts.pScore > level0AND ts.pScore <= level1) AS ExamCount
FROM tbLevel AS tl;
levels = '10,20,30,40,50,60,70,80,90,100';
levels = '40,60,80,100';