如果雇用日期大于年初,则为12个月平均值

时间:2013-05-31 01:17:00

标签: sql

我成功计算了一个员工12个月的平均销售额,基于年度的开始和结束,在这种情况下是2013年。但是,当员工在年初之后开始时,他们的平均值必须从他们的聘用日期。我需要弄清楚如何计算在年初之后开始雇用日期的员工的12个月平均值。

这是我目前的查询:

    DECLARE @begDt DATETIME, @endDt DATETIME
    SET @begDt = DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, -1, GETDATE())), 0) 
    SET @endDt = DATEADD(MILLISECOND, -3, DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, -1, GETDATE())) + 1, 0))

  select
  [Account Executive] = v.Name_AccountExecutive
, [YTD Production] = cast(sum (case when v.Process_FundingDt between @begDt and @endDt then v.Loan_LoanAmt else 0 end) as int)
, [Monthly Average] = cast(sum (case when v.Process_FundingDt between @begDt and @endDt then v.Loan_LoanAmt else 0 end) 
  / (case when @begDt = '1/1/2012' then 
      case when v.Name_AccountExecutive = 'HIEB, BRANDON' then 7 when v.Name_AccountExecutive = 'AMORATI, KAREN' then 8 else 12 end
      else (datepart(m, @endDt)) end) as int)
from LOS.LoanView v
group by v.Name_AccountExecutive

1 个答案:

答案 0 :(得分:0)

嘿伙计们只是想回答这个问题,因为我没有正确地形成这个问题而且这看起来很混乱,但这是我正在做的事情。如果有更好的方式随意评论,但这现在适用。

, [Monthly Average] = cast(sum (case when v.Process_FundingDt between @begDt and @endDt then v.Loan_LoanAmt else 0 end) as int)
/(case when aa.End_Date is NULL then 
      (
      case when Year(aa.Hire_Date)< Year(@begDt) and Year(@begDt)<Year(getdate()) then 12 -- hired anytime before the currrent reporting year and current reporting year is not current year.
            when Year(aa.Hire_Date) < Year(@begDt) and Year(@begDt)=Year(getdate()) then MONTH(getdate())-- hired  anytime before the currrent reporting year  and current reporting year is the current year
            when Year(aa.Hire_Date) = Year(@begDt) and Year(@begDt)<Year(getdate()) then 12-Month(aa.Hire_Date) -- hired same as reporting year but the reporting year is not same as current year
            when Year(aa.Hire_Date) = Year(@begDt) and Year(@begDt)=Year(getdate()) then MONTH(getdate())-Month(aa.Hire_Date) -- hired same as reporting year and the reporting year is  same as current year
      end
      )
      else
      (
      Case when Year(aa.End_Date)<Year(@begDt)  then NULL
            when Year(aa.End_Date)=Year(@begDt) and YEAR(aa.Hire_Date)<Year(aa.End_Date)  then MONTH(aa.End_Date) -- end date is same as reporting year, was hired preivous year, current year doesn't matter
            when Year(aa.End_Date)=Year(@begDt)and YEAR(aa.Hire_Date)=Year(aa.End_Date)  then MONTH(aa.End_Date)-MONTH(aa.Hire_Date) -- end year, start year and reporting year is same, current year doesn't matter
            when  Year(aa.End_Date)>Year(@begDt) and YEAR(aa.Hire_Date)=Year(@begDt) then 12-MONTH(aa.Hire_Date)
            when  Year(aa.End_Date)>Year(@begDt) and YEAR(aa.Hire_Date)<Year(@begDt) then 12
      end
      )
      end
)