ORacle SQL query to find end date from max value of a column
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
精彩评论