开发者

ORacle SQL query to find end date from max value of a column

开发者 https://www.devze.com 2023-01-31 23:21 出处:网络
e.g. My table contains records as shown below. EmpNamePaycodeApplyDateAmt. of Hrs emp1vacation5/1/20108 emp1vacation5/2/20108

e.g. My table contains records as shown below.

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

I am trying to get the 开发者_StackOverflow中文版output like this...

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

Can any one help me to fix this.

Thanks Mart


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


If you are looking to have more complex data and only add up consecutive days (as @Dan mentioned in a comment) then you will need a more complicated query.

Something that might solve your problem is shown below. This is a modification of the code from 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 
0

精彩评论

暂无评论...
验证码 换一张
取 消