如果年份为null,则需要每年的最后一个值和之前的值

时间:2016-07-14 22:47:14

标签: sql-server-2008 group-by

我的员工每年都会改变费率,有时一年会改变几次。试图找出一年中的最后一次利率,如果一年中没有利率变化,那么就要拉出前一年的价值。我已经获得了今年的最后一项记录,但是在使用没有变化的年份的前一个值时遇到了麻烦。理想情况下,我每年都会得到一个结果。但是说到这一点,我意识到这可能会很快失控。因此,如果有一个2008年和2010年的费率,而不是2009年,我需要2008年的费率出现在2009年。使用SQL Server 2008 R2 考虑做一个十字架或外部应用日历,但我一直转过身来。 我已经使用Todd Fifield帖子创建了日历,只添加了Yr和Year值。 http://www.sqlservercentral.com/articles/T-SQL/70482/

这是我到目前为止所拥有的

with YrHist as
(
select h.HRCo, h.HRRef, h.EffectiveDate, YEAR(h.EffectiveDate) as EffectiveYr,DATEADD(m,DATEDIFF(m,0,h.EffectiveDate),0) as EffMth, h.Type, h.NewSalary, h.OldSalary

from HRSH h
        left outer join PREHName p on h.HRCo=p.PRCo and h.HRRef=p.Employee
)

select distinct ROW_NUMBER() over(Order By tt.HRCo,tt.HRRef,tt.EffectiveYr) as RowID,
tt.HRCo, tt.HRRef,tt.EffMth, tt.EffectiveYr, tt.EffectiveDate, tt.Type, tt.NewSalary as MaxRateForYr, tt.OldSalary

from YrHist as tt

        inner join
            (select HRCo, HRRef, EffectiveYr, MAX(EffectiveDate) as MaxEffDate
            from YrHist
            Group By HRCo, HRRef, EffectiveYr) as m on tt.EffectiveYr=m.EffectiveYr and tt.EffectiveDate=m.MaxEffDate and tt.HRCo=m.HRCo and tt.HRRef=m.HRRef

Example of Results

2 个答案:

答案 0 :(得分:1)

结束换桌子;而不是查看保持工资变化的表格,我使用表格查看历史记录,并使用每年的最长日期。

答案 1 :(得分:0)

您可以使用此示例并解决您的问题

假设您有一个包含所有年份的日历表

create table #cal (Yr int)
insert into #cal values (2010), (2011), (2012), (2013), (2014), (2015), (2016)

并假设这是您拥有每年费率的表格

with x as (
  select 1 AS ID, 2010 AS Y, 58 AS Rate
  union
  select 2, 2011, 48
  union
  select 3, 2013, 38
  union
  select 4, 2013, 59
  union
  select 5, 2014, 68
  union
  select 6, 2014, 78
  union
  select 7, 2014, 56
  union
  select 8, 2016, 45
)
select * into #t from x

然后此查询将为您提供您要查找的结果

select Yr
, isnull(max(cc.Rate), (select top 1 Rate from #t where Y < Yr order by ID desc)) Rate
from #cal
    left join #t ot on #cal.Yr = ot.Y
    outer apply (select top 1 ID, Rate from #t where Y = ot.Y order by ID desc) AS cc
group by #cal.Yr

<强>结果

╔══════╦══════╗
║ Yr   ║ Rate ║
╠══════╬══════╣
║ 2010 ║ 58   ║
╠══════╬══════╣
║ 2011 ║ 48   ║
╠══════╬══════╣
║ 2012 ║ 48   ║
╠══════╬══════╣
║ 2013 ║ 59   ║
╠══════╬══════╣
║ 2014 ║ 56   ║
╠══════╬══════╣
║ 2015 ║ 56   ║
╠══════╬══════╣
║ 2016 ║ 45   ║
╚══════╩══════╝