-1

CTE を使用して日付の範囲を生成する次の LOJ クエリを使用しています。

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 テーブルには、住宅ローン 12345678 の行が 2 つだけあります。

ここに画像の説明を入力


ここで解決!

@inquiryStartDate DateTime を宣言します。@inquiryEndDate DateTime を宣言します。@inquiryMortgageNumber nvarchar(50); を宣言します。

SET @inquiryStartDate = '2013-07-01'; SET @inquiryEndDate = '2013-07-31'; SET @お問い合わせ住宅番号 = '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;
4

2 に答える 2

2

これを試して:

With DateRange As (
SELECT ID, Date
FROM     d_Dates
WHERE  (Date BETWEEN @inquiryStartDate AND @inquiryEndDate)
 )
   Select d.ID, d.Date, s.MortgageNumber, s.Investor_ID
   From DateRange d
      Left Join f_MortgageSnapshots s
         On d.ID = s.SnapshotDate_ID
            And  MortgageNumber = @inquiryMortgageNumber;

また、CTE を使用する場合、実際に日付テーブルをヒットする必要はありません

With DateRange As (
SELECT ID, inquiryStartDate ADate
Union All
Select ID + 1, ADate + 1
FROM DateRange 
Where ADate < @inquiryEndDate)
Select d.ID, d.Date, s.MortgageNumber, s.Investor_ID
From DateRange d
    Left Join f_MortgageSnapshots s
        On d.ID = s.SnapshotDate_ID
           And  MortgageNumber = @inquiryMortgageNumber
OPTION (MAXRECURSION 2000);

MortgageNumbernull 行におよびのデフォルト値を表示する場合は、次の 関数Investor_IDを使用します。Coalesce()

With DateRange As (
SELECT ID, inquiryStartDate ADate
Union All
Select ID + 1, ADate + 1
FROM DateRange 
Where ADate < @inquiryEndDate)
Select d.ID, d.Date, 
   Coalesce(s.MortgageNumber, 'DefaultMortgageNumber') MortgageNumber,
   Coalesce(s.Investor_ID , -1) Investor_ID
From DateRange d
    Left Join f_MortgageSnapshots s
        On d.ID = s.SnapshotDate_ID
           And  MortgageNumber = @inquiryMortgageNumber
OPTION (MAXRECURSION 2000);
于 2013-10-11T21:02:41.790 に答える