日期:2014-05-17  浏览次数:20884 次

统计每个学生的优良差,这语句该怎么写?
一张成绩表:
姓名 语文 数学 英语
张三 90 100 58
李四 68 79 85
成绩不少于80为优,60到80之间为良,小于60为差。
统计出每个人各科成绩的优良差,写出sql语句。
这该怎么写?


------解决方案--------------------
SQL code
select 姓名,
            (case when 语文>=80 then '优'
                  when 语文<80 and 语文 >=60 then '良' 
                  else '60' end) as '语文',
            (case when 数学>=80 then '优'
                  when 数学<80 and 数学 >=60 then '良' 
                  else '60' end)      as '数学', 
            (case when 英语>=80 then '优'
                  when 英语<80 and 英语 >=60 then '良' 
                  else '60' end) as '英语'
from 成绩表

------解决方案--------------------
SQL code

--楼上60那里写错了吧,应该是差吧!
select 姓名,
            (case when 语文>=80 then '优'
                  when 语文<80 and 语文 >=60 then '良' 
                  else '差' end) as '语文',
            (case when 数学>=80 then '优'
                  when 数学<80 and 数学 >=60 then '良' 
                  else '差' end)      as '数学', 
            (case when 英语>=80 then '优'
                  when 英语<80 and 英语 >=60 then '良' 
                  else '差' end) as '英语'
from 成绩表

------解决方案--------------------
首先,lz 你要认识到这个问题就是把成绩转化而已;
其次,case when 可移植性高,decode是oracle的方言,具体用哪个楼主自己思量;
最后,我闲着蛋疼,给lz写了下:

SQL code
SQL> ed
已写入 file afiedt.buf

  1  create table test(
  2             name varchar2(20),
  3             chinese number,
  4             maths number,
  5*            english number)
  6  /

表已创建。

SQL> ed
已写入 file afiedt.buf

  1  insert into test
  2* values('张三', 90, 100, 58)
SQL> /

已创建 1 行。

SQL> ed
已写入 file afiedt.buf

  1  insert into test
  2* values('李四', 68, 79, 85)
SQL> /

已创建 1 行。

SQL> select * from test;

NAME                    CHINESE      MATHS    ENGLISH
-------------------- ---------- ---------- ----------
张三                         90        100         58
李四                         68         79         85


SQL> ed
已写入 file afiedt.buf

  1    select name,
  2                (case when chinese>=80 then '优'
  3                      when chinese<80 and chinese >=60 then '良'
  4                      else '差'
  5                               end)  as chinese,
  6                (case when maths>=80 then '优'
  7                      when maths<80 and maths >=60 then '良'
  8                      else '差' end)  as maths,
  9                (case when english>=80 then '优'
 10                      when english<80 and english >=60 then '良'
 11                      else '差' end) as english
 12*  from test
 13  /

NAME                 CH MA EN
-------------------- -- -- --
张三                 优 优 差
李四                 良 良 优