如何使用时间间隔逐组选择?

时间:2017-05-29 07:52:31

标签: sql oracle select group-by sql-order-by

我有一张桌子:EXAM_LIST

"EXAM_ID"    "EXAM_NAME"        "EXAM_START_TIME"     "EXAM_END_TIME"         "STUDENT_ID"

1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:10:00      123  
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:78:00      65
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:38:00      77
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:61:00      99
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:45:00      13
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:39:00      98
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:48:00      14
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:50:00      5
1               ENGLISH     01-JAN-13 00:00:00    01-JAN-13 00:65:00      1

我尝试使用该查询但它只计算(GOOD - 3,AVERAGE - 3,POOR - 3)

select 
          SUM(CASE WHEN NVL(EXAM.TIME,0) >= 0  AND NVL(EXAM.TIME,0) <= 40 THEN 1 ELSE 0 END) AS GOOD,
          SUM(CASE WHEN NVL(EXAM.TIME,0) > 40  AND NVL(EXAM.TIME,0)<= 60 THEN 1 ELSE 0 END) AS AVERAGE,
          SUM(CASE WHEN NVL(EXAM.TIME,0) > 60 AND NVL(EXAM.TIME,0) <= 80 THEN 1 ELSE 0 END) AS POOR,

    from 
    (  SELECT 
    TO_NUMBER(TO_DATE(EXAM_END_TIME,'YYYYMMDDHH24MISS')-to_date(EXAM_START_TIME,'YYYYMMDDHH24MISS'))*24*60 AS TIME
     FROM  EXAM_LIST B, CLASS C
   WHERE 
   A.EXAM_ID = B.ID

    AND EXAM_START_TIME IS NOT NULL) EXAM

但我需要一些喜欢的结果:

"EXAM_ID"   "EXAM_START_TIME"     "EXAM_END_TINE"            
GOOD
1            01-JAN-13 00:00:00    01-JAN-13 00:10:00      
1            01-JAN-13 00:00:00    01-JAN-13 00:39:00     
1            01-JAN-13 00:00:00    01-JAN-13 00:38:00     

AVERAGE
1            01-JAN-13 00:00:00    01-JAN-13 00:45:00      
1            01-JAN-13 00:00:00    01-JAN-13 00:48:00     
1            01-JAN-13 00:00:00    01-JAN-13 00:50:00  

POOR
1            01-JAN-13 00:00:00    01-JAN-13 00:65:00      
1            01-JAN-13 00:00:00    01-JAN-13 00:78:00     
1            01-JAN-13 00:00:00    01-JAN-13 00:61:00     

如何按上述方式逐组选择?

1 个答案:

答案 0 :(得分:0)

您似乎主要想按好,平均和差来订购行:

select *
from
( 
  select
    exam_id, 
    exam_start_time,
    exam_end_time,
    case 
      when (exam_end_time - exam_start_time) * 24 * 60 <= 40 then 'good' 
      when (exam_end_time - exam_start_time) * 24 * 60 <= 60 then 'average' 
      when (exam_end_time - exam_start_time) * 24 * 60 <= 80 then 'poor' 
      else 'oops'
    end as result
  from exam_list
  where exam_start_time is not null
)
where result in ('good', 'average', 'poor')
order by case result when 'good' then 1 when 'average' then 2 else 3 end;