Postgres sql 8.4分别使用时差和日期差异

时间:2013-08-05 14:03:44

标签: sql postgresql-8.4

我有这个问题,我无法解决它,因为我认为这在sql中是不可能的

我有这张桌子

Shedule
    id_emp    Name       `time initial` time end   
    1         juan`       09:00`          12:00
    2        Francisco    10:00           11:30
    3        Sebastian    11:00           15:00
    6        Roberto      15:00           18:00


Suspension
id_emp          suspension_initial     suspension_end
1                    2013-06-01           2013-06-01
2                    2013-06-01           2013-06-03
3                    2013-06-03           2013-06-04 
6                    2013-06-01           2013-06-01
2                    2013-07-01           2013-07-01
3                    2013-07-05           2013-07-05
1                    2013-07-06           2013-07-06

我想赶上工作时间((time_end- time_initial) - 暂停)(如果我有1天的停课时间是一个小时的例子:胡安每天工作3小时,他在六月和一个停工1天7月份停课的那天。所以我假设他在一个月内工作3 * 20(小时*工作日) - 3月6日和3小时7月 我怎样才能得到这个结果

id_emp name `       June-2013               July-2013
1       Juan           57 (hours Worked)        57 (hours Worked)
2       Francisco      24 (hours worked)        27 (hours worked)
3       Sebastián
6       Roberto

1 个答案:

答案 0 :(得分:0)

<强> Here is the SQLFiddel Demo

以下是您可以尝试的查询

select EmpHrs.ID_EMP,
       EmpHrs.Name,
       (
        (EmpHrs.NOOFHRS*20)-
        (EmpHrs.NOOFHRS*
          JuneSuspension.MONTHSUSPENSION)
       )  as "June-2013",
       (
        (EmpHrs.NOOFHRS*20)-
        (EmpHrs.NOOFHRS*
          JulySuspension.MONTHSUSPENSION)
       )  as "July-2013"

from 
(
select ID_EMP,NAME,
       Extract(Hours from time_end-time_initial)+
       Extract(Minutes from time_end-time_initial)/60 as NoOfHrs
  from schedule
) EmpHrs
Left join
(select ID_EMP,to_char(to_timestamp (Extract(Month from suspension_initial)::text, 'MM'),'Mon') as MonthIni,(suspension_end::date - suspension_initial::date)+1 MonthSuspension
from suspension
where Extract(Month from suspension_initial) = 6) JuneSuspension
On JuneSuspension.ID_EMP = EmpHrs.ID_EMP
Left join
(select ID_EMP,to_char(to_timestamp (Extract(Month from suspension_initial)::text, 'MM'),'Mon') as MonthIni,(suspension_end::date - suspension_initial::date)+1 MonthSuspension
from suspension
where Extract(Month from suspension_initial) = 7) JulySuspension
On JulySuspension.ID_EMP = EmpHrs.ID_EMP