--分數段分布
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';?