我正在使用以下 LOJ 查询,它使用 CTE 来生成日期范围:
Declare @inquiryStartDate DateTime;
Declare @inquiryEndDate DateTime;
Declare @inquiryMortgageNumber nvarchar(50);
SET @inquiryStartDate = '2013-07-01';
SET @inquiryEndDate = '2013-07-31';
SET @inquiryMortgageNumber = '12345678';
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
WHERE f_MortgageSnapshots.MortgageNumber = @inquiryMortgageNumber;
我得到了这个:
但我想要这个:
我究竟做错了什么?
快速说明,f_MortgageSnapshots 表中只有 2 行用于抵押贷款 12345678。
解决方案在这里!
声明@inquiryStartDate 日期时间;声明@inquiryEndDate 日期时间;声明@inquiryMortgageNumber nvarchar(50);
SET @inquiryStartDate = '2013-07-01'; SET @inquiryEndDate = '2013-07-31'; SET @inquiryMortgageNumber = '7078575';
With DateRange As (
SELECT ID, d_Dates.Date
FROM d_Dates
WHERE (d_Dates.Date BETWEEN @inquiryStartDate AND @inquiryEndDate)
)
Select DateRange.ID, DateRange.Date,f_MortgageSnapshots.MortgageNumber, f_MortgageSnapshots.Investor_ID
From DateRange Left Join f_MortgageSnapshots
On DateRange.ID = f_MortgageSnapshots.SnapshotDate_ID
And MortgageNumber = @inquiryMortgageNumber;