SQL - 如何查找年初至今的金额?

时间:2010-08-13 19:51:55

标签: sql sql-server

假设我有一张名为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

如何找到特定员工和付费期的年初至今小时数?

对于上面的例子,我想要:

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)

到目前为止,我已经尝试了这一点,但总计似乎已经关闭了:

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

(如果重要的话,我在SQL Server 2005中)

2 个答案:

答案 0 :(得分:4)

这将使用SELECT中的子查询获得运行总计。

努力让马克获得第28名。

select employee, 
        payperiod,
        (SELECT sum ([hours]) FROM @hours f2 
             WHERE f2.payperiod <= f.payperiod and f2.employee=f.employee) as hh

 from @hours as f
 where  YEAR(payperiod) = year(getdate()) --current year.
 group by employee, payperiod
 order by payperiod

答案 1 :(得分:1)

有可能有更好的方式来获得今年的第一个,但这似乎更容易。

Select 
    H.employee
  , H.payperiod
  , (Select Sum(H1.hours) 
     From hours as H1         
     Where H1.employee = H.employee 
        and H1.payperiod <= H.payperiod
    ) as hours_YTD
from hours as H
where Year(H.payperiod) = Year(GetDate()
  and H.payperiod <= GetDate()
group by employee
   , payperiod

*最后一行将需要一个全新的宗教信仰,除非它在桌子上或者你没有告诉我们。