8

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

我的问题类似于此处提出的问题:追溯生效日期更改与重叠日期,但我不处理追溯或重叠日期范围。

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

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子查询中使用运算符绕着圈子根据收费日期隔离正确的费率,但没有任何运气。

我很感激任何帮助!

4

1 回答 1

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)
于 2012-04-17T18:41:23.523 回答