Let's say I have a table like this called hours:
employee, payperiod, hours
greg, 1/31/2010, 12
greg, 1/31/2010, 15
mark, 1/31/2010, 10
mark, 1/31/2010, 11
greg, 2/28/2010, 12
greg, 2/28/2010, 15
greg, 2/28/2010, 4
How would I find the year to date hours for a given employee and payperiod?
For the above example I'd want to get to:
employee, payperiod, hours_YTD
greg, 1/31/2010, 27
mark, 1/31/2010, 21
greg, 2/28/2010, 58
mark, 2/28/2010, 21 (this row is a nice to have, I can live without it if it's too tricky)
So far I've tried this but the total seems to be off:
select employee,payperiod,sum(hours) from hours h1
join hours h2 on h2.payperiod<=h1.payperiod and h2.payperiod>=1/1/2010
and h1.employee=h2.employee
group by h1.employee, h1.payperiod
(I'm in SQL Server 2005 if it matters)