简体   繁体   English

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

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

eg 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 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. 如果您希望获得更复杂的数据并且仅连续添加几天(如@Dan在评论中提到的),那么您将需要一个更复杂的查询。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM