SQL查询根据收费日期选择有效的成本费率

时间:2012-04-17 18:18:29

标签: sql sql-server sql-server-2008

SQL新手在这里。我正在尝试生成一个成本核算查询,该查询输出员工时间卡信息并根据有效的员工成本核算率计算成本。

我的问题类似于此处提出的问题:Retro-active effective date changes with overlapping dates但我不会处理追溯活动或重叠日期范围。

表格示例(费率表中的空值表示当前费率):

CREATE TABLE Emp_Rate
(
    Emp int,
    Rate money,
    Rate_Start datetime,
    Rate_Exp datetime
)

CREATE TABLE Emp_Time
(
    Emp int,
    Chrg_Date datetime,
    Chrg_Code varchar(10),
    Chrg_Hrs decimal(8, 2)
)

Insert into Emp_Rate (Emp,Rate,Rate_Start,Rate_Exp) Values ('1','20','5/1/09','4/30/10')
Insert into Emp_Rate (Emp,Rate,Rate_Start,Rate_Exp) Values ('1','21','5/1/10','4/30/11')
Insert into Emp_Rate (Emp,Rate,Rate_Start,Rate_Exp) Values ('1','22','5/1/11',NULL)

Insert into Emp_Time (Emp,Chrg_Date,Chrg_Code,Chrg_Hrs) Values ('1','5/10/09','B','8')
Insert into Emp_Time (Emp,Chrg_Date,Chrg_Code,Chrg_Hrs) Values ('1','5/10/10','B','8')
Insert into Emp_Time (Emp,Chrg_Date,Chrg_Code,Chrg_Hrs) Values ('1','5/10/11','B','8')

查询(返回由多个速率条目引起的欺骗(显然)):

Select  Emp_Time.Emp,
        Cast(Emp_Time.Chrg_Date as DATE) as 'Chrg_Date',
        Emp_Time.Chrg_Code,
        Emp_Time.Chrg_Hrs,
        Emp_Rate.Rate,
        Emp_Time.Chrg_Hrs * Emp_Rate.Rate as 'Cost'

From    Emp_Time inner join
        Emp_Rate on Emp_Rate.Emp = Emp_Time.Emp

Order By [Emp],[Chrg_Date]

期望的输出:

Emp Chrg_Date   Chrg_Code   Chrg_Hrs    Rate    Cost
1   2009-05-10  B           8.00        20.00   160.00
1   2010-05-10  B           8.00        21.00   168.00
1   2011-05-10  B           8.00        22.00   176.00

我在子查询中使用Between运算符在圈子中四处走动,根据收费日期隔离正确的费率,但没有运气。

我感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

您未指定DBMS类型,以下答案适用于sql-server。我确信还有其他方法可以执行此操作,但这种方式会将null Rate_Exp日期替换为当前日期。

Select  et.Emp,
        Cast(et.Chrg_Date as DATEtime) as 'Chrg_Date',
        et.Chrg_Code,
        et.Chrg_Hrs,
        er.Rate,
        et.Chrg_Hrs * er.Rate as 'Cost'
From  Emp_Time et
inner join 
(
    SELECT Emp
        , Rate
        , Rate_Start
        , CASE
            WHEN Rate_Exp is Null
            THEN Convert(varchar(10), getdate(), 101)
            ELSE Rate_Exp
          END as Rate_Exp
    FROM Emp_Rate 
)er 
    on er.Emp = et.Emp
WHERE (et.Chrg_Date BETWEEN er.Rate_Start AND er.Rate_Exp)
Order By et.Emp,et.Chrg_Date

或者使用CASE条款中的WHERE声明:

Select  et.Emp,
        Cast(et.Chrg_Date as DATEtime) as 'Chrg_Date',
        et.Chrg_Code,
        et.Chrg_Hrs,
        er.Rate,
        et.Chrg_Hrs * er.Rate as 'Cost'
From  Emp_Time et
inner join Emp_Rate er
    on er.Emp = et.Emp
WHERE (et.Chrg_Date 
        BETWEEN er.Rate_Start 
                AND CASE WHEN er.Rate_Exp Is Null 
            THEN  Convert(varchar(10), getdate(), 101)
            ELSE er.Rate_Exp END)