if-then-else语句 - 需要逻辑

时间:2014-04-29 05:45:12

标签: oracle

以下是包含表和插入值的测试用例

create table students (
           name varchar2(25 BYTE),
           joined_date DATE,
           exam_type VARCHAR2(25 BYTE),
           SCORE NUMBER(2,1),
           CUT_OFF_DATE DATE
     );
        insert into students values('john','26-mar-14','SCREEN',7.6,'10-apr-14');
        insert into students values('john','10-Apr-14','RETEST',8.0,'10-apr-14');

我正在尝试使用该学生姓名的分数返回唯一记录。我使用CASE,但它实际上并不像使用控制语句那样“IF-THEN-else”。

select name,
       joined_date,
       case 
            ---something like IF statment if below[b] statement 1[/b] --is true then it
            --should return below statement
            when exam_type ='SCREEN' and score between 8.0 and 10.0
            then score
            ----[b]statement 2[/b] --if above expr fails, the below to be executed
            when exam_type ='RETEST' and score between 8.0 and 10.0
            and joined_date >= cut_off_date
            then score
            else null
       end result
from students;

output
    NAME    JOINED_DATE RESULT
    john    26-03-14    
    john    10-04-14    8

在上面的结果集中,我只需将得分'8'和'John'作为唯一记录?像这样,有超过数百万条记录需要计算。

需要逻辑吗?请

2 个答案:

答案 0 :(得分:0)

这是CASE WHEN语句的默认行为,当条件均不为TRUE时,它将置为NULL。您可以更改以下查询以获得预期结果。

SELECT * FROM
(
 select name,
       joined_date,
       case 
            ---something like IF statment if below[b] statement 1[/b] --is true then it
            --should return below statement
            when exam_type ='SCREEN' and score between 8.0 and 10.0
            then score
            --[b]statement 2[/b] --if above expr fails, the below to be executed
            when exam_type ='RETEST' and score between 8.0 and 10.0
            and joined_date >= cut_off_date
            then score
       end result
 from students
 ) main where main.result IS NOT NULL;

检查SQL FIDDLE

答案 1 :(得分:0)

这是另一种选择。根据此标准选择单个分数:学生的最高分数,最早的joined_date和cut_off_date以及最少的exam_type值(按字母顺序排列)。

SELECT 
  DISTINCT
  s1.name
  ,s1.joined_date
  ,s1.exam_type
  ,s1.score
  ,s1.cut_off_date
FROM students s1
INNER JOIN
(SELECT name, joined_date, exam_type, score, cut_off_date,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY score desc, joined_date, exam_type, cut_off_date) rn
 FROM students
 WHERE 
     (exam_type ='SCREEN' and score between 8.0 and 10.0)
  or (exam_type ='RETEST' and score between 8.3 and 10.0 and joined_date >= cut_off_date)
) s2
ON s1.name = s2.name
AND s1.joined_date = s2.joined_date
AND s1.exam_type = s2.exam_type
AND s1.cut_off_date = s2.cut_off_date
WHERE s2.rn = 1;

SQL Fiddle