sql结合查询结果

时间:2014-12-04 20:04:19

标签: sql oracle

我有以下查询:

select 
    employee.last_name || ', ' || employee.first_name name, 
    job.title,
    daystotime(time_sheet.finish_date_time - time_sheet.start_date_time) time
from 
    employee 
inner join 
    employee_case on employee.employee_id = employee_case.employee 
inner join
    time_sheet on time_sheet.employee_case = employee_case.employee_case_id 
inner join 
    job on employee.job = job.job_id
where 
    employee_case.case = 1
order by 
    employee.last_name;

这给出了以下结果:

enter image description here

但是,我需要的是能够将同一员工的时间列组合起来给出总时间。

我创建的用于生成时间字段的函数是:

create or replace function DaysToTime(p_val in number)
return varchar2
is
  l_days     number;
  l_hours    number;
  l_minutes  number;
  l_seconds  number;
begin
  l_days := p_val;
  l_Hours := (l_days - trunc(l_days)) *24;
  l_minutes := (l_hours - trunc(l_hours)) * 60;
  l_seconds := (l_minutes - trunc(l_minutes)) * 60;
 return to_char(trunc(l_days), 'fm09')  ||':'||
        to_char(trunc(l_hours), 'fm09')  ||':'||
        to_char(trunc(l_minutes), 'fm09')||':'||
        to_char(trunc(l_seconds), 'fm09');
end;

感谢您提供任何帮助,如果您需要任何其他信息,请告诉我,

1 个答案:

答案 0 :(得分:1)

在函数+ GROUP BY中使用SUM:

select 
    employee.last_name || ', ' || employee.first_name name, 
    job.title,
    daystotime(sum(time_sheet.finish_date_time - time_sheet.start_date_time)) time
from 
    employee 
inner join 
    employee_case on employee.employee_id = employee_case.employee 
inner join
    time_sheet on time_sheet.employee_case = employee_case.employee_case_id 
inner join 
    job on employee.job = job.job_id
where 
    employee_case.case = 1
group by employee.last_name, employee.first_name, 
         job.title  
order by 
    employee.last_name;

P.S。 Oracle中有一种INTERVAL类型(也许您不需要自己的功能):

select numtodsinterval(d2 - d1, 'day') from
(select to_date('02 12:44:01', 'DDHH24:MI:SS') d1, 
        to_date('03 12:44:05', 'DDHH24:MI:SS') d2 
 from dual)