根据服务日期加入正确的预算日期范围字段

时间:2013-09-09 16:18:02

标签: sql sql-server-2008 date

我有两张桌子需要加入。第一个表包含服务的日期和该服务的成本。第二个表包括给定时间段内服务的最大预算。下面的服务有两个预算,一个开始'4/2/2012'并结束'4/2/2013',但在'4/2/2014'结束的同一天更新。该服务于2013年4月15日进行 因此,我需要附上与服务时间相关的预算:'4/2/2013'到'2014年4月2日'。由于一个预算在四月结束,并在四月更新。在下面的计划中,两个预算都已加入。

我需要加入start_date和end_date,其中DOSSTART属于两个日期之间。

CREATE TABLE #Service_Budget(
        ID int,
        SERV_Type int,
        Start_DT  datetime,
        End_DT  datetime,
        Budget int, 
        NUMBER_OF_MONTHS_OF_SERVICES int
    );
INSERT INTO #Service_Budget VALUES 
(13946, 5,  '4/2/2012', '4/2/2013', 622.4, 12), 
(13946, 5,  '4/2/2013', '4/2/2014', 788.4, 12) 

CREATE TABLE #Service_Visits(
ID  int,
Service_Type int,   
DOSStart datetime,
BillableUnits int,
RATE_AMOUNT int
 );

INSERT INTO #Service_Visits VALUES
(13946, 5,  '4/15/2013', 3,75.5)


SELECT    
a.ID,
a.Service_Type,
a.DOSStart,
MONTH(a.DOSStart) AS Month,
YEAR(a.DOSStart) AS Year,
MONTH(b.START_DT) AS Start_Month,
YEAR(b.START_DT) AS Start_Year,
b.Start_DT,
b.End_DT,
 a.RATE_AMOUNT,
 (a.RATE_AMOUNT * a.BillableUnits) as Total,  
 b.Budget,
 b.NUMBER_OF_MONTHS_OF_SERVICES
 FROM #Service_Visits as a join #Service_Budget as  b
   on a.ID=b.ID

这就是我得到的:

ID  Service_Type    DOSStart    Month   Year    Start_Month Start_Year  Start_DT    End_DT  RATE_AMOUNT Total   Budget  NUMBER_OF_MONTHS_OF_SERVICES
13946   5   2013-04-15 00:00:00.000 4   2013    4   2012    2012-04-02 00:00:00.000 2013-04-02 00:00:00.000 75  225 622 12
13946   5   2013-04-15 00:00:00.000 4   2013    4   2013    2013-04-02 00:00:00.000 2014-04-02 00:00:00.000 75  225 788 12

注意两个预算都已加入,请注意与DOSSTART日期相关的预算。

1 个答案:

答案 0 :(得分:1)

您可以使用BETWEEN子句on a.ID=b.ID AND DOSStart BETWEEN Start_DT AND End_DT。试试这个:

CREATE TABLE #Service_Budget(
        ID int,
        SERV_Type int,
        Start_DT  datetime,
        End_DT  datetime,
        Budget int, 
        NUMBER_OF_MONTHS_OF_SERVICES int
    );
INSERT INTO #Service_Budget VALUES 
(13946, 5,  '4/2/2012', '4/2/2013', 622.4, 12), 
(13946, 5,  '4/2/2013', '4/2/2014', 788.4, 12) 

CREATE TABLE #Service_Visits(
ID  int,
Service_Type int,   
DOSStart datetime,
BillableUnits int,
RATE_AMOUNT int
 );

INSERT INTO #Service_Visits VALUES
(13946, 5,  '4/15/2013', 3,75.5)


SELECT    
a.ID,
a.Service_Type,
a.DOSStart,
MONTH(a.DOSStart) AS Month,
YEAR(a.DOSStart) AS Year,
MONTH(b.START_DT) AS Start_Month,
YEAR(b.START_DT) AS Start_Year,
b.Start_DT,
b.End_DT,
 a.RATE_AMOUNT,
 (a.RATE_AMOUNT * a.BillableUnits) as Total,  
 b.Budget,
 b.NUMBER_OF_MONTHS_OF_SERVICES
 FROM #Service_Visits as a join #Service_Budget as  b
   on a.ID=b.ID AND DOSStart BETWEEN Start_DT AND End_DT