左外连接仅日期范围不按预期工作

时间:2013-10-23 23:34:54

标签: sql tsql join

我最初发布了这个问题here但遗憾的是现在我必须转储按揭号码过滤器。事实证明这是一种痛苦。

我正在使用以下LOJ查询,该查询使用CTE生成一系列日期:

Declare @inquiryStartDate DateTime;
Declare @inquiryEndDate DateTime;

SET @inquiryStartDate = '2013-07-01';
SET @inquiryEndDate = '2013-07-31';

With DateRange As (
    SELECT ID, Date
    FROM     d_Dates
    WHERE  (Date BETWEEN @inquiryStartDate AND @inquiryEndDate)
)
Select DateRange.ID, DateRange.Date,f_MortgageSnapshots.MortgageNumber, f_MortgageSnapshots.Investor_ID
From DateRange
LEFT OUTER JOIN f_MortgageSnapshots On DateRange.ID = f_MortgageSnapshots.SnapshotDate_ID

我得到的是这样的东西:

enter image description here

但我想要这个:

enter image description here

我做错了什么?在这种情况下,我不能在表之间进行左连接吗?

快速注意,f_MortgageSnapshots表中只有2行可用于抵押12345678。

enter image description here

对于那些想知道的人,这里是d_Dates表:

enter image description here

1 个答案:

答案 0 :(得分:1)

看起来d_dates在查询日期范围内的每个可能日期都不包含一行。

尝试类似: -

create function [dbo].BuildDataRange
(
    @StartDate date,
    @EndDate date
)
returns @returntable table
(
    ID int,
    [Date] date
)
as
begin
    while @StartDate<=@EndDate begin
        insert into @returntable (ID, [Date]) values (
            DATEPART(year,@StartDate)*10000 + 
            DATEPART(month,@StartDate)*100 + 
            DATEPART(day,@StartDate),
            @StartDate)
        set @StartDate=DATEADD(day,1,@StartDate)
    end
    return
end
go

然后你应该能够: -

Declare @inquiryStartDate DateTime;
Declare @inquiryEndDate DateTime;

SET @inquiryStartDate = '2013-07-01';
SET @inquiryEndDate = '2013-07-31';

select *
from [dbo].BuildDataRange(@inquiryStartDate, @inquiryEndDate) dr
left join f_MortgageSnapshots On dr.ID = f_MortgageSnapshots.SnapshotDate_ID