DECLARE @i INT = 0;
DECLARE @testDate DATE = '03/01/2022'

WHILE @i < 30
BEGIN
    SELECT * FROM Application as AppMain
    /*
    This query is designed to pull in applications that require a decline letter to be sent to the customer
    through OSG. They should be added to the CollectionsLetter file sent to OSG.
    */
    -- This left join pulls in the most recent syndication information | AppSynA = ApplicationSyndication table
    LEFT JOIN (SELECT AppSynA.AppKey, AppSyndicationStatusId FROM AppSyndication as AppSynA
        LEFT JOIN
        ( --Here we select only the most recent record date for each record so that the 
        --left join above does not pull multiple syndication ids for each app
            SELECT AppKey, MAX(RecordUpdateDate) as NewRec -- NewRec = Newest Syndication Record Date
            FROM [LEAFCore].[dbo].[AppSyndication]
            GROUP BY [dbo].[AppSyndication].AppKey) as NewestSynd on AppSynA.AppKey=NewestSynd.AppKey
            WHERE AppSynA.RecordUpdateDate = NewestSynd.NewRec
        ) as AppSynRec on AppMain.AppKey=AppSynRec.AppKey

    -- This left join pulls in the most recent Decision code and the date that it occurred | ADCH == AppDecisionCodeHistory
    LEFT JOIN (SELECT ADCH.AppKey, HistoryDate, DecisionCodeKey as CurrentDecisionCode FROM AppDecisionCodeHistory as ADCH
        LEFT JOIN
        ( -- Here we select only the most recent record date for each record so that the 
            SELECT AppKey, Max(HistoryDate) as DecDate -- DecDate = Decision Date
            FROM AppDecisionCodeHistory
            GROUP BY AppKey) AS DecNewRec on ADCH.AppKey=DecNewRec.AppKey -- DecNewRec = Newest Decision Record
            WHERE ADCH.HistoryDate = DecNewRec.DecDate
        ) as AppDecRec on AppMain.AppKey = AppDecRec.AppKey -- AppDecRec = ApplicationDecisionRecord

    -- This left join pulls in the business type using the customer key from the main app table
    LEFT JOIN (SELECT CustomerKey, BusinessTypeID FROM Customer) as CustInfo on AppMain.CustomerKey=CustInfo.CustomerKey
    -- We can limit the query so that it's a bit faster
    WHERE AppMain.CreateDate > '2022-01-01 00:00:01.000' 
    -- Only get apps declined between 13 & 14 days ago
    AND HistoryDate BETWEEN DATEADD(day,-14,GETDATE()) AND DATEADD(day,-13,GETDATE())
    -- Only get apps that are declined (6) or auto-rejected (17)
    AND CurrentDecisionCode in (6,17)
    -- Only pull apps with no syndication record or have been rejected for syndication
    AND (AppSyndicationStatusId is NULL OR AppSyndicationStatusId = 3)
    -- Only pull Small Business Finance Group (137505)
    AND (AppMain.ProductLineKey = '137505' OR AppMain.PromotionKey = 183172)
    AND (
        -- Only pull apps that are for customers, promotion Penskee (183172)
        CustomerApp = 1 OR AppMain.PromotionKey = 183172
    )
    SET @i = @i + 1;
END;