記得以前面試時遇到的,感覺這個問題比較經典,所以后來整理了下。
題目描述是這樣的(憑印象):
請用一條sql統計出每個班級中,20-50分、50-70分、70-100分的人數,
已知:表(exam),有如下字段:class(班級)、name(姓名)、score(分數);
查詢顯示格式:
這是個典型的分段又分組的查詢案例,難點就是考慮到按班級分組的同時按成績分段查詢。
表數據如下:
select count_abc.class 班級, sum(case when count_abc.a is null then 0 else 1 end) '20-50的人數', sum(case when count_abc.b is null then 0 else 1 end) '50-70的人數', sum(case when count_abc.c is null then 0 else 1 end) '70-100的人數' from ( select case when score between 20 and 50 then 1 end a, case when score between 50 and 70 then 1 end b, case when score between 70 and 100 then 1 end c, class from exam ) count_abc group by count_abc.class;
分組不用說是group by,分段常用是between ... and ...,關鍵是如何串聯。因為每一條數據都有這樣一個特性:最多在一個分數段里。容易想到用case when 語句來表達這種互斥關系。
於是想到把所有的分數段分布情況,並用a,b,c區分,再根據標記不同進行累計求和。
上面的sql還可以簡化:
select count_abc.class 班級, sum(count_abc.a) '20-50的人數', sum(count_abc.b) '50-70的人數', sum(count_abc.c) '70-100的人數' from ( select case when score between 20 and 50 then 1 else 0 end a, case when score between 50 and 70 then 1 else 0 end b, case when score between 70 and 100 then 1 else 0 end c, class from exam ) count_abc group by count_abc.class;