由一條sql語句引發的學習之二

select m.*,case
when  m.max_num > n.maxvalue then '被考覈' else '正常' end as maxvalue , 
nvl(n.CATEGORY,'其他') from (
select 'didi' x1 ,a.templateid ,b.template_name ,sum(a.num) send_num,count(1) user_num,max(a.num) max_num,trunc(sum(a.num)/count(1)) seg_num
from (
select phone_no, templateid, count(1)num
  from math_score
 where send_time > trunc(sysdate)
 group by  phone_no,  templateid
having count(1) > $anum) a, school_info b
where a.templateid =  b.template_id  ${tiaojian}
group by a.templateid,b.template_name
union all
select 'didi',a.templateid,b.template_name  ,sum(a.num) send_num,count(1) user_num,max(a.num) max_num,trunc(sum(a.num)/count(1)) seg_num
from (
select phone_no, templateid, count(1)num
  from english_score
 where send_time > trunc(sysdate) 
 group by  phone_no,  templateid
having count(1) > $anum) a, school_info b
where a.templateid =  b.template_id  ${tiaojian}
group by a.templateid,b.template_name
union all
select 'didi',a.templateid,b.template_name  ,sum(a.num) send_num,count(1) user_num,max(a.num) max_num,trunc(sum(a.num)/count(1)) seg_num
from (
select phone_no, templateid, count(1)num
  from chinese_score
 where send_time > trunc(sysdate)
 group by  phone_no,  templateid
having count(1) > $anum) a, school_info b
where a.templateid =  b.template_id  ${tiaojian}
group by a.templateid,b.template_name)  m ,school_info n
where m.templateid = n.template_id 
order by user_num desc;

  場景:

  求取一個學校內,每個(語文\數學\英語)老師所帶學生的班級名、班級總分、班級人數、最高分,平均分、及格率,及格率是否符合正常情況(考覈老師)

  school_info表字段:老師id、班級、班級人數、及格率...

  math_score表字段:老師id、班級、手機號、學生信息、數學成績...

  關鍵語法解析:

  1、NVL函數:從兩個表達式返回一個非 null 值。

  2、case用法:詳細解析

  3、from+表名跟from+select語句作用一樣。

  4、Union和Union All區別:詳解

       Union:對兩個結果集進行並集操作,不包括重複行,同時進行默認規則的排序;

       Union All:對兩個結果集進行並集操作,包括重複行,不進行排序;

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章