ORacle SQL查询从列的最大值中查找结束日期

时间:2010-12-22 10:22:23

标签: sql oracle

e.g。 我的表包含如下所示的记录。

EmpName       Paycode      ApplyDate            Amt. of Hrs
emp1          vacation      5/1/2010                     8
emp1          vacation      5/2/2010                     8
emp1          vacation      5/3/2010                     8

我试图得到像这样的输出......

Emp Name  Paycode      Leave Start Date    Leave End Date    TotalHrs
emp1      vacation         5/1/2010           5/3/2010           24

任何人都可以帮我解决这个问题。

由于 玛特

2 个答案:

答案 0 :(得分:3)

select
  empname
  , paycode
  , min(applyDate) as leave_start_date
  , max(applyDate) as leave_end_date
  , sum(amt_of_hrs) as total_hours
from TableEmp
group by empname, paycode

答案 1 :(得分:2)

如果您希望获得更复杂的数据并且只连续添加日期(如评论中提到的@Dan)那么您将需要更复杂的查询。

可能解决您问题的方法如下所示。这是对this question

代码的修改
WITH test_data AS (
  SELECT  'emp1' as empname, 'vacation' as paycode, date '2010-05-01' as applydate, 8 as numhours from dual union all
  SELECT  'emp1' as empname, 'vacation' as paycode, date '2010-05-02' as applydate, 8 as numhours from dual union all
  SELECT  'emp1' as empname, 'vacation' as paycode, date '2010-05-03' as applydate, 8 as numhours from dual union all
  SELECT  'emp2' as empname, 'vacation' as paycode, date '2010-05-01' as applydate, 8 as numhours from dual union all
  SELECT  'emp2' as empname, 'vacation' as paycode, date '2010-05-02' as applydate, 8 as numhours from dual union all
  SELECT  'emp1' as empname, 'vacation' as paycode, date '2010-07-05' as applydate, 8 as numhours from dual 
)
select 
      empname,
      paycode,
      min(applydate) as startdate,
      max(applydate) as startdate,
      sum(numhours) as toalhours
from ( 
  select 
      empname,
      paycode,
      applydate,
      numhours,
/* number the blocks sequentially */
    sum(is_block_start) over (partition by empname, paycode order by applydate) as block_num
  from ( 
    select 
      empname,
      paycode,
      applydate,
      numhours,
/* Mark the start of each block */
      case 
        when applydate = prev_applydate + 1 then 0 else 1 end as is_block_start
    from ( 
      select 
        empname,
        paycode,
        applydate,
        numhours,
        lag(applydate) over (partition by empname, paycode order by applydate) prev_applydate
      from test_data
    )
  )
)
group by empname, paycode, block_num