SlideShare ist ein Scribd-Unternehmen logo
1 von 7
IF OBJECT_ID('tempdb..#InvoiceLookup') IS NOT NULL
BEGIN
DROP TABLE #InvoiceLookup
END
IF OBJECT_ID('tempdb..#LeaseLevelDetail') IS NOT NULL
BEGIN
DROP TABLE #LeaseLevelDetail
END
IF OBJECT_ID('tempdb..#UpgradedLeases') IS NOT NULL
BEGIN
DROP TABLE #UpgradedLeases
END
IF OBJECT_ID('tempdb..#FirstAppearence') IS NOT NULL
BEGIN
DROP TABLE #FirstAppearence
END
IF OBJECT_ID('tempdb..#OldLeases') IS NOT NULL
BEGIN
DROP TABLE #OldLeases
END
IF OBJECT_ID('tempdb..#CombinedOldNew_Upgrades') IS NOT NULL
BEGIN
DROP TABLE #CombinedOldNew_Upgrades
END
IF OBJECT_ID('tempdb..#CumulativePremiums') IS NOT NULL
BEGIN
DROP TABLE #CumulativePremiums
END
IF OBJECT_ID('tempdb..#MiscLeases') IS NOT NULL
BEGIN
DROP TABLE #MiscLeases
END
IF OBJECT_ID('tempdb..#5ColumnAddition') IS NOT NULL
BEGIN
DROP TABLE #5ColumnAddition
END
IF OBJECT_ID('tempdb..#DRV2') IS NOT NULL
BEGIN
DROP TABLE #DRV2
END
IF OBJECT_ID('tempdb..#InvMisc') IS NOT NULL
BEGIN
DROP TABLE #InvMisc
END
IF OBJECT_ID('tempdb..#InvExcess') IS NOT NULL
BEGIN
DROP TABLE #InvExcess
END
IF OBJECT_ID('tempdb..#InvPostExcess') IS NOT NULL
BEGIN
DROP TABLE #InvPostExcess
END
--picks the first instance of misc/e/pe appearance. necessary to obtain the correct
'billed months' parameter for [StandardRentBilled] calculation below
SELECT leaseID, billedmonths, invoicetype, invoicedate, ROW_NUMBER () OVER(PARTITION BY
leaseID ORDER BY invoicedate) AS Instance
INTO #InvoiceLookup
FROM lease.vw_lease_Invoice_current
ORDER BY leaseID
SELECT leaseID, SUM(FinalRentAmountDue) AS FRAD, SUM(FinalDeviceAmountDue) AS FDAD
INTO #InvMisc
FROM lease.vw_lease_invoice_current
WHERE InvoiceType = 2
GROUP BY leaseID, InvoiceType
SELECT leaseID, SUM(FinalRentAmountDue) AS FRAD
INTO #InvExcess
FROM lease.vw_lease_invoice_current
WHERE InvoiceType = 3
GROUP BY leaseID, InvoiceType
SELECT leaseID, SUM(FinalRentAmountDue) AS FRAD
INTO #InvPostExcess
FROM lease.vw_lease_invoice_current
WHERE InvoiceType = 4
GROUP BY leaseID, InvoiceType
SELECT DISTINCT
rvclose.LeaseScheduleNumber,
rvclose.RemainingPayments,
rvcurr.Residual_Value
INTO #DRV2
FROM lease.vw_lease_RVatCLosing_current RVclose
LEFT JOIN
Lease.vw_Lease_CurrentRV_current RVcurr
ON YEAR(RVcurr.ResidualValueMonth) = YEAR(DATEADD(mm, 2,
rvclose.LeaseEndingMonth))
AND MONTH(RVcurr.ResidualValueMonth) = MONTH(DATEADD(mm, 2,
rvclose.LeaseEndingMonth))
AND RVcurr.SKU# = (rvclose.Make +' '+ rvclose.Model)
SELECT
a.ScheduleNumber
,a.leaseID
,a.OldLeaseSequenceNumber
,[OldLeaseID] = c.leaseID
,b.createddate
,[FirstAppearence] = ROW_NUMBER () OVER(PARTITION BY b.leaseID ORDER BY b.createddate)
,b.TermStartDate
,[NewMonthlyRent] = b.MonthlyLeaseAmountBilled
,[NewLeaseTermInMonths] = b.terminmonths
INTO #FirstAppearence
FROM lease.vw_lease_current a
INNER JOIN
lease.leaseEquipment b
ON a.leaseID = b.leaseID
INNER JOIN lease.vw_lease_current c
ON a.OldLeaseSequenceNumber = c.LeaseSequenceNumber
WHERE a.OldLeaseSequenceNumber IS NOT NULL
AND a.OldLeaseSequenceNumber <> ''
SELECT
ScheduleNumber
,leaseID
,OldLeaseSequenceNumber
,[OldLeaseID]
,[NewMonthlyRent]
,[NewLeaseTermInMonths]
,TermStartDate
,[FirstLMSAppearence] = createddate
,[FirstInvoiceUnderNewRent] =
CASE
WHEN DATEPART(DAY, createddate) IN (1,2)
THEN CAST(STR(DATEPART(YEAR,createddate))+'-'+
STR(DATEPART(MONTH,createddate)) +'-'+ STR('05') AS DATE)
ELSE CAST(STR(DATEPART(YEAR,createddate))+'-'+ STR(DATEPART(MONTH,DATEADD(MONTH,
1, createddate))) +'-'+ STR('05') AS DATE)
END
INTO #UpgradedLeases
FROM #FirstAppearence
WHERE [FirstAppearence] = 1
SELECT
a.scheduleNumber
,a.leaseID
,a.LeaseSequenceNumber
,[OldLeaseAmount] = b.MonthlyLeaseAmountBilled
,[OldMasterLease] = c.RemainingPayments
,[OldLeasePaymentsRemainingAtUpgrade] = c.RemainingPayments-(DATEDIFF(MONTH,'2-29-
16',@LastInvDt)-1)
,[OldLeaseFinalRent] = b.FinalPaymentAmount
INTO #OldLeases
FROM lease.vw_lease_current a
INNER JOIN lease.vw_LeaseEquipment_current b
ON a.LeaseID = b.LeaseID
AND b.IsActive = 1
INNER JOIN lease.vw_Lease_RVatClosing_current c
on a.ScheduleNumber = c.LeaseScheduleNumber
WHERE LeaseSequenceNumber IN (SELECT OldLeaseSequenceNumber FROM #upgradedleases)
SELECT
a.schedulenumber
,[OldleaseID] = b.leaseID
,[NewLeaseID] = a.leaseID
,a.[FirstLMSAppearence]
,[NewLeaseStartDate] = a.termstartdate
,[NewLeaseTermInMonths] = a.NewLeaseTermInMonths
,[OldMasterLease] = b.[OldMasterLease]
,[OldMonthlyRent] = b.[OldLeaseAmount]
,[OldLeaseFinalRent] = b.OldLeaseFinalRent
,[NewMonthlyRent] = a.[NewMonthlyRent]
,[Premium] = a.[NewMonthlyRent] - b.[OldLeaseAmount]
INTO #CombinedOldNew_Upgrades
FROM #UpgradedLeases a
INNER JOIN #OldLeases b
ON a.oldleasesequencenumber = b.leasesequencenumber
SELECT
a.ScheduleNumber
,a.leaseID
,a.LeaseNumber
,[Standard Rent] = LE.MonthlyLeaseAmountBilled
,[Billed Months] = -- this assumes the month that the report is running has already
undergone invoicing process. (counts current month as billed)
CASE
WHEN up.leaseID IS NULL
AND old.leaseID IS NOT NULL
THEN DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),c.FirstLMSAppearence) --old
lease
WHEN up.leaseID IS NOT null
THEN DATEDIFF(MONTH,up.FirstLMSAppearence,@LastInvDt) --upgraded lease
WHEN up.leaseID IS NULL --not upgraded
AND old.leaseID IS NULL
THEN
CASE
WHEN Inv.leaseID IS NOT NULL
AND Inv.invoicetype = 2 --misc
THEN DATEDIFF(mm,'2-29-16', Inv.invoicedate) - 2 --
subtracting 2 backs out one month for billing in arrears and one month for the misc inv
WHEN Inv.leaseID IS NOT NULL
AND Inv.invoicetype IN (3,4) --excess or post excess
THEN DRV2.RemainingPayments
ELSE DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),@LastInvDt) --
still in standard
END
END
,[Upgrade IND] =
CASE
WHEN up.leaseID IS NULL
THEN 0
WHEN up.leaseID IS NOT NULL
THEN 1
END
,[Old Lease IND]=
CASE
WHEN old.leaseID IS NULL
THEN 0
WHEN old.leaseID IS NOT NULL
THEN 1
END
,[Misc IND] =
CASE
WHEN
(
Inv.leaseID IS NOT NULL
AND Inv.invoicetype = 2
)
THEN 1
ELSE 0
END
,[ExcessPostExcess IND] =
CASE
WHEN
(
Inv.leaseID IS NOT NULL
AND Inv.invoicetype IN (3,4)
)
THEN 1
ELSE 0
END
--,[-A Tranche IND] =
--CASE
-- WHEN a.TrancheNumber = '-A'
-- THEN 1
-- ELSE 0
--END
,[Standard Rent Billed] =
CASE
WHEN up.leaseID IS NULL
AND old.leaseID IS NOT NULL--dead lease
THEN (DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),c.FirstLMSAppearence)) *
LE.MonthlyLeaseAmountBilled
WHEN up.leaseID IS NOT null--upgraded lease
THEN (DATEDIFF(MONTH,up.FirstLMSAppearence,@LastInvDt)) *
LE.MonthlyLeaseAmountBilled
WHEN up.leaseID IS NULL
AND old.leaseID IS NULL --not upgraded
THEN
CASE
WHEN Inv.leaseID IS NOT NULL
AND Inv.invoicetype = 2 --misc
THEN (DATEDIFF(mm,'2-29-16', Inv.invoicedate) - 2) *
LE.MonthlyLeaseAmountBilled
WHEN Inv.leaseID IS NOT NULL
AND Inv.invoicetype IN (3,4) --excess or post excess
THEN ((DRV2.RemainingPayments-1) *
LE.MonthlyLeaseAmountBilled)+ LE.FinalPaymentAmount
ELSE (DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),@LastInvDt)) *
LE.MonthlyLeaseAmountBilled --still in standard
END
END
,[Remaining Residual Value] =
CASE
WHEN Inv.leaseid IS NOT NULL --in excess, post excess, or was misc
THEN
CASE
WHEN DRV2.Residual_Value - ISNULL(InvM.FDAD,0) -
ISNULL(InvE.FRAD,0) - ISNULL(InvPE.FRAD,0) < 0
THEN 0
WHEN DRV2.Residual_Value - ISNULL(InvM.FDAD,0) -
ISNULL(InvE.FRAD,0) - ISNULL(InvPE.FRAD,0) > 0
THEN DRV2.Residual_Value - ISNULL(InvM.FDAD,0) -
ISNULL(InvE.FRAD,0) - ISNULL(InvPE.FRAD,0)
END
ELSE DRV2.residual_value -- still in standard, include full DRV
END
,[Total Accelerated Rent Invoiced] = InvM.FRAD
,[Total Accelerated Device Invoiced] = InvM.FDAD
INTO #LeaseLevelDetail
FROM lease.vw_lease_current a
LEFT JOIN
(SELECT leaseID, billedmonths, invoicetype, invoicedate FROM #InvoiceLookup WHERE
Instance = 1) Inv
ON a.LeaseID = Inv.LeaseID
LEFT JOIN
lease.vw_leaseEquipment_current LE
ON a.LeaseID = LE.LeaseID
AND LE.IsActive = 1
LEFT JOIN
lease.vw_leasedetail_current d
ON a.LeaseID = d.LeaseID
LEFT JOIN
#UpgradedLeases up
ON a.LeaseID = up.leaseID
LEFT JOIN
#OldLeases old
ON a.LeaseID = old.leaseID
LEFT JOIN
#CombinedOldNew_Upgrades c
ON a.leaseID = c.oldleaseID
LEFT JOIN
#DRV2 DRV2
ON a.ScheduleNumber = DRV2.LeaseScheduleNumber
LEFT JOIN
#InvMisc InvM
on a.LeaseID = InvM.LeaseID
LEFT JOIN
#InvExcess InvE
on a.LeaseID = InvE.LeaseID
LEFT JOIN
#InvPostExcess InvPE
on a.LeaseID = InvPE.LeaseID
WHERE a.TrancheNumber = '2'
SELECT
b.ScheduleNumber
,b.leaseID
,[Billed Months Under Upgrade] = b.[Billed Months]
,[Monthly Premium] =
CASE
WHEN a.Premium < 0
THEN 0
ELSE a.Premium
END
,[Cumulative Premium] =
CASE
WHEN ((a.OldMasterLease-(DATEDIFF(MONTH,'2-29-16',c.FirstInvoiceUnderNewRent)-2))
* a.NewMonthlyRent)-(((a.OldMasterLease-(DATEDIFF(MONTH,'2-29-
16',c.FirstInvoiceUnderNewRent)-1)) * a.OldMonthlyRent) + a.OldLeaseFinalRent) < 0
THEN 0
ELSE ((a.OldMasterLease-(DATEDIFF(MONTH,'2-29-16',c.FirstInvoiceUnderNewRent)-2))
* a.NewMonthlyRent)-(((a.OldMasterLease-(DATEDIFF(MONTH,'2-29-
16',c.FirstInvoiceUnderNewRent)-1)) * a.OldMonthlyRent) + a.OldLeaseFinalRent)
END
INTO #CumulativePremiums
FROM #CombinedOldNew_Upgrades a
INNER JOIN #LeaseLevelDetail b
ON a.newleaseID = b.leaseID
INNER JOIN #UpgradedLeases c
ON a.NewLeaseID = c.LeaseID
WHERE b.[upgrade IND] = 1
SELECT
[ScheduleNumber]
,[LeaseID]
,[DRV] = ISNULL(b.Residual_Value,0)
INTO #MiscLeases
FROM #LeaseLevelDetail a
INNER JOIN #DRV2 b
ON a.ScheduleNumber = b.LeaseScheduleNumber
WHERE [Misc IND] = 1
SELECT
a.ScheduleNumber
,[Standard Rent Billed] = SUM(ISNULL(a.[Standard Rent Billed],0))
,[Remaining Residual Value] = SUM(ISNULL(a.[Remaining Residual Value],0))
,[Monthly Premium] = SUM(ISNULL(B.[Monthly Premium],0))
,[Cumulative Premium] = SUM(ISNULL(B.[Cumulative Premium],0))
,[DRV of Misc Invoiced Leases] = SUM(ISNULL(c.[DRV],0))
,[Total Accelerated Rent Invoiced] = SUM(ISNULL(a.[Total Accelerated Rent Invoiced],0))
,[Total Accelerated Device Invoiced] = SUM(ISNULL(a.[Total Accelerated Device
Invoiced],0))
INTO #5ColumnAddition
FROM #LeaseLevelDetail a
LEFT JOIN #CumulativePremiums b
ON a.leaseID = b.leaseID
LEFT JOIN #MiscLeases c
ON a.leaseID = c.leaseID
GROUP BY a.schedulenumber
SELECT a.*
,b.[Standard Rent Billed]
,b.[Remaining Residual Value]
,b.[Monthly Premium]
,b.[Cumulative Premium]
,b.[DRV of Misc Invoiced Leases]
,b.[Total Accelerated Rent Invoiced]
,b.[Total Accelerated Device Invoiced]
FROM #FinalDynamicTranche a
INNER JOIN #5ColumnAddition b
ON a.[MasterLease Schedule Number] = b.ScheduleNumber

Weitere ähnliche Inhalte

Was ist angesagt?

Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
Clinton Dreisbach
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8
katbailey
 

Was ist angesagt? (17)

Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machine
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patterns
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Two Trains and Other Refactoring Analogies
Two Trains and Other Refactoring AnalogiesTwo Trains and Other Refactoring Analogies
Two Trains and Other Refactoring Analogies
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 

Andere mochten auch (10)

Blocked Drain – Hire A Professional Cleaner!
Blocked Drain – Hire A Professional Cleaner! Blocked Drain – Hire A Professional Cleaner!
Blocked Drain – Hire A Professional Cleaner!
 
งานนำเสนอ2
งานนำเสนอ2งานนำเสนอ2
งานนำเสนอ2
 
Picture story amora
Picture story amoraPicture story amora
Picture story amora
 
A short analysis of green investment potential in europe and beyond
A short analysis of green investment potential in europe and beyondA short analysis of green investment potential in europe and beyond
A short analysis of green investment potential in europe and beyond
 
Теплосчетчик Ultraheat t550
Теплосчетчик Ultraheat t550Теплосчетчик Ultraheat t550
Теплосчетчик Ultraheat t550
 
ROLES DE LA COMPUTADORA
ROLES DE LA COMPUTADORAROLES DE LA COMPUTADORA
ROLES DE LA COMPUTADORA
 
resume-kenjie-2016
resume-kenjie-2016resume-kenjie-2016
resume-kenjie-2016
 
Teoria de kaizen
Teoria de kaizenTeoria de kaizen
Teoria de kaizen
 
Farbtest
FarbtestFarbtest
Farbtest
 
Panorama de la educacion 2016
Panorama de la educacion 2016Panorama de la educacion 2016
Panorama de la educacion 2016
 

Ähnlich wie SQLscript

Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdfHelp with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
ezycolours78
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
Evan Schultz
 
Set Focus SQL Portfolio
Set Focus SQL PortfolioSet Focus SQL Portfolio
Set Focus SQL Portfolio
brentbybee
 
1582627
15826271582627
1582627
tabish
 
I need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdfI need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdf
pnaran46
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
Nawaz Sk
 

Ähnlich wie SQLscript (20)

Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdfHelp with Starting out with visual basic 7th edition chapter 6 Progr.pdf
Help with Starting out with visual basic 7th edition chapter 6 Progr.pdf
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
How to transfer bad PLSQL into good (AAAPEKS23)
How to transfer bad PLSQL into good (AAAPEKS23)How to transfer bad PLSQL into good (AAAPEKS23)
How to transfer bad PLSQL into good (AAAPEKS23)
 
Standing the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternStanding the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider Pattern
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
 
Set Focus SQL Portfolio
Set Focus SQL PortfolioSet Focus SQL Portfolio
Set Focus SQL Portfolio
 
project
projectproject
project
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
 
1582627
15826271582627
1582627
 
黑豹 ch4 ddd pattern pracrice
黑豹 ch4 ddd pattern pracrice黑豹 ch4 ddd pattern pracrice
黑豹 ch4 ddd pattern pracrice
 
Oracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationOracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional Compilation
 
I need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdfI need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdf
 
Using Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your DataUsing Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your Data
 
Using Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your DataUsing Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your Data
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Into React-DOM.pptx
Into React-DOM.pptxInto React-DOM.pptx
Into React-DOM.pptx
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 
Xenogenetics
XenogeneticsXenogenetics
Xenogenetics
 

SQLscript

  • 1. IF OBJECT_ID('tempdb..#InvoiceLookup') IS NOT NULL BEGIN DROP TABLE #InvoiceLookup END IF OBJECT_ID('tempdb..#LeaseLevelDetail') IS NOT NULL BEGIN DROP TABLE #LeaseLevelDetail END IF OBJECT_ID('tempdb..#UpgradedLeases') IS NOT NULL BEGIN DROP TABLE #UpgradedLeases END IF OBJECT_ID('tempdb..#FirstAppearence') IS NOT NULL BEGIN DROP TABLE #FirstAppearence END IF OBJECT_ID('tempdb..#OldLeases') IS NOT NULL BEGIN DROP TABLE #OldLeases END IF OBJECT_ID('tempdb..#CombinedOldNew_Upgrades') IS NOT NULL BEGIN DROP TABLE #CombinedOldNew_Upgrades END IF OBJECT_ID('tempdb..#CumulativePremiums') IS NOT NULL BEGIN DROP TABLE #CumulativePremiums END IF OBJECT_ID('tempdb..#MiscLeases') IS NOT NULL BEGIN DROP TABLE #MiscLeases END IF OBJECT_ID('tempdb..#5ColumnAddition') IS NOT NULL BEGIN DROP TABLE #5ColumnAddition END IF OBJECT_ID('tempdb..#DRV2') IS NOT NULL BEGIN DROP TABLE #DRV2 END IF OBJECT_ID('tempdb..#InvMisc') IS NOT NULL BEGIN DROP TABLE #InvMisc END IF OBJECT_ID('tempdb..#InvExcess') IS NOT NULL BEGIN DROP TABLE #InvExcess END IF OBJECT_ID('tempdb..#InvPostExcess') IS NOT NULL BEGIN DROP TABLE #InvPostExcess END --picks the first instance of misc/e/pe appearance. necessary to obtain the correct 'billed months' parameter for [StandardRentBilled] calculation below SELECT leaseID, billedmonths, invoicetype, invoicedate, ROW_NUMBER () OVER(PARTITION BY leaseID ORDER BY invoicedate) AS Instance INTO #InvoiceLookup
  • 2. FROM lease.vw_lease_Invoice_current ORDER BY leaseID SELECT leaseID, SUM(FinalRentAmountDue) AS FRAD, SUM(FinalDeviceAmountDue) AS FDAD INTO #InvMisc FROM lease.vw_lease_invoice_current WHERE InvoiceType = 2 GROUP BY leaseID, InvoiceType SELECT leaseID, SUM(FinalRentAmountDue) AS FRAD INTO #InvExcess FROM lease.vw_lease_invoice_current WHERE InvoiceType = 3 GROUP BY leaseID, InvoiceType SELECT leaseID, SUM(FinalRentAmountDue) AS FRAD INTO #InvPostExcess FROM lease.vw_lease_invoice_current WHERE InvoiceType = 4 GROUP BY leaseID, InvoiceType SELECT DISTINCT rvclose.LeaseScheduleNumber, rvclose.RemainingPayments, rvcurr.Residual_Value INTO #DRV2 FROM lease.vw_lease_RVatCLosing_current RVclose LEFT JOIN Lease.vw_Lease_CurrentRV_current RVcurr ON YEAR(RVcurr.ResidualValueMonth) = YEAR(DATEADD(mm, 2, rvclose.LeaseEndingMonth)) AND MONTH(RVcurr.ResidualValueMonth) = MONTH(DATEADD(mm, 2, rvclose.LeaseEndingMonth)) AND RVcurr.SKU# = (rvclose.Make +' '+ rvclose.Model) SELECT a.ScheduleNumber ,a.leaseID ,a.OldLeaseSequenceNumber ,[OldLeaseID] = c.leaseID ,b.createddate ,[FirstAppearence] = ROW_NUMBER () OVER(PARTITION BY b.leaseID ORDER BY b.createddate) ,b.TermStartDate ,[NewMonthlyRent] = b.MonthlyLeaseAmountBilled ,[NewLeaseTermInMonths] = b.terminmonths INTO #FirstAppearence FROM lease.vw_lease_current a INNER JOIN lease.leaseEquipment b ON a.leaseID = b.leaseID INNER JOIN lease.vw_lease_current c ON a.OldLeaseSequenceNumber = c.LeaseSequenceNumber WHERE a.OldLeaseSequenceNumber IS NOT NULL AND a.OldLeaseSequenceNumber <> '' SELECT ScheduleNumber
  • 3. ,leaseID ,OldLeaseSequenceNumber ,[OldLeaseID] ,[NewMonthlyRent] ,[NewLeaseTermInMonths] ,TermStartDate ,[FirstLMSAppearence] = createddate ,[FirstInvoiceUnderNewRent] = CASE WHEN DATEPART(DAY, createddate) IN (1,2) THEN CAST(STR(DATEPART(YEAR,createddate))+'-'+ STR(DATEPART(MONTH,createddate)) +'-'+ STR('05') AS DATE) ELSE CAST(STR(DATEPART(YEAR,createddate))+'-'+ STR(DATEPART(MONTH,DATEADD(MONTH, 1, createddate))) +'-'+ STR('05') AS DATE) END INTO #UpgradedLeases FROM #FirstAppearence WHERE [FirstAppearence] = 1 SELECT a.scheduleNumber ,a.leaseID ,a.LeaseSequenceNumber ,[OldLeaseAmount] = b.MonthlyLeaseAmountBilled ,[OldMasterLease] = c.RemainingPayments ,[OldLeasePaymentsRemainingAtUpgrade] = c.RemainingPayments-(DATEDIFF(MONTH,'2-29- 16',@LastInvDt)-1) ,[OldLeaseFinalRent] = b.FinalPaymentAmount INTO #OldLeases FROM lease.vw_lease_current a INNER JOIN lease.vw_LeaseEquipment_current b ON a.LeaseID = b.LeaseID AND b.IsActive = 1 INNER JOIN lease.vw_Lease_RVatClosing_current c on a.ScheduleNumber = c.LeaseScheduleNumber WHERE LeaseSequenceNumber IN (SELECT OldLeaseSequenceNumber FROM #upgradedleases) SELECT a.schedulenumber ,[OldleaseID] = b.leaseID ,[NewLeaseID] = a.leaseID ,a.[FirstLMSAppearence] ,[NewLeaseStartDate] = a.termstartdate ,[NewLeaseTermInMonths] = a.NewLeaseTermInMonths ,[OldMasterLease] = b.[OldMasterLease] ,[OldMonthlyRent] = b.[OldLeaseAmount] ,[OldLeaseFinalRent] = b.OldLeaseFinalRent ,[NewMonthlyRent] = a.[NewMonthlyRent] ,[Premium] = a.[NewMonthlyRent] - b.[OldLeaseAmount] INTO #CombinedOldNew_Upgrades FROM #UpgradedLeases a INNER JOIN #OldLeases b ON a.oldleasesequencenumber = b.leasesequencenumber SELECT a.ScheduleNumber ,a.leaseID
  • 4. ,a.LeaseNumber ,[Standard Rent] = LE.MonthlyLeaseAmountBilled ,[Billed Months] = -- this assumes the month that the report is running has already undergone invoicing process. (counts current month as billed) CASE WHEN up.leaseID IS NULL AND old.leaseID IS NOT NULL THEN DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),c.FirstLMSAppearence) --old lease WHEN up.leaseID IS NOT null THEN DATEDIFF(MONTH,up.FirstLMSAppearence,@LastInvDt) --upgraded lease WHEN up.leaseID IS NULL --not upgraded AND old.leaseID IS NULL THEN CASE WHEN Inv.leaseID IS NOT NULL AND Inv.invoicetype = 2 --misc THEN DATEDIFF(mm,'2-29-16', Inv.invoicedate) - 2 -- subtracting 2 backs out one month for billing in arrears and one month for the misc inv WHEN Inv.leaseID IS NOT NULL AND Inv.invoicetype IN (3,4) --excess or post excess THEN DRV2.RemainingPayments ELSE DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),@LastInvDt) -- still in standard END END ,[Upgrade IND] = CASE WHEN up.leaseID IS NULL THEN 0 WHEN up.leaseID IS NOT NULL THEN 1 END ,[Old Lease IND]= CASE WHEN old.leaseID IS NULL THEN 0 WHEN old.leaseID IS NOT NULL THEN 1 END ,[Misc IND] = CASE WHEN ( Inv.leaseID IS NOT NULL AND Inv.invoicetype = 2 ) THEN 1 ELSE 0 END ,[ExcessPostExcess IND] = CASE WHEN ( Inv.leaseID IS NOT NULL AND Inv.invoicetype IN (3,4) ) THEN 1
  • 5. ELSE 0 END --,[-A Tranche IND] = --CASE -- WHEN a.TrancheNumber = '-A' -- THEN 1 -- ELSE 0 --END ,[Standard Rent Billed] = CASE WHEN up.leaseID IS NULL AND old.leaseID IS NOT NULL--dead lease THEN (DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),c.FirstLMSAppearence)) * LE.MonthlyLeaseAmountBilled WHEN up.leaseID IS NOT null--upgraded lease THEN (DATEDIFF(MONTH,up.FirstLMSAppearence,@LastInvDt)) * LE.MonthlyLeaseAmountBilled WHEN up.leaseID IS NULL AND old.leaseID IS NULL --not upgraded THEN CASE WHEN Inv.leaseID IS NOT NULL AND Inv.invoicetype = 2 --misc THEN (DATEDIFF(mm,'2-29-16', Inv.invoicedate) - 2) * LE.MonthlyLeaseAmountBilled WHEN Inv.leaseID IS NOT NULL AND Inv.invoicetype IN (3,4) --excess or post excess THEN ((DRV2.RemainingPayments-1) * LE.MonthlyLeaseAmountBilled)+ LE.FinalPaymentAmount ELSE (DATEDIFF(MONTH,DATEADD(MONTH,1,'2-29-16'),@LastInvDt)) * LE.MonthlyLeaseAmountBilled --still in standard END END ,[Remaining Residual Value] = CASE WHEN Inv.leaseid IS NOT NULL --in excess, post excess, or was misc THEN CASE WHEN DRV2.Residual_Value - ISNULL(InvM.FDAD,0) - ISNULL(InvE.FRAD,0) - ISNULL(InvPE.FRAD,0) < 0 THEN 0 WHEN DRV2.Residual_Value - ISNULL(InvM.FDAD,0) - ISNULL(InvE.FRAD,0) - ISNULL(InvPE.FRAD,0) > 0 THEN DRV2.Residual_Value - ISNULL(InvM.FDAD,0) - ISNULL(InvE.FRAD,0) - ISNULL(InvPE.FRAD,0) END ELSE DRV2.residual_value -- still in standard, include full DRV END ,[Total Accelerated Rent Invoiced] = InvM.FRAD ,[Total Accelerated Device Invoiced] = InvM.FDAD INTO #LeaseLevelDetail FROM lease.vw_lease_current a LEFT JOIN (SELECT leaseID, billedmonths, invoicetype, invoicedate FROM #InvoiceLookup WHERE Instance = 1) Inv
  • 6. ON a.LeaseID = Inv.LeaseID LEFT JOIN lease.vw_leaseEquipment_current LE ON a.LeaseID = LE.LeaseID AND LE.IsActive = 1 LEFT JOIN lease.vw_leasedetail_current d ON a.LeaseID = d.LeaseID LEFT JOIN #UpgradedLeases up ON a.LeaseID = up.leaseID LEFT JOIN #OldLeases old ON a.LeaseID = old.leaseID LEFT JOIN #CombinedOldNew_Upgrades c ON a.leaseID = c.oldleaseID LEFT JOIN #DRV2 DRV2 ON a.ScheduleNumber = DRV2.LeaseScheduleNumber LEFT JOIN #InvMisc InvM on a.LeaseID = InvM.LeaseID LEFT JOIN #InvExcess InvE on a.LeaseID = InvE.LeaseID LEFT JOIN #InvPostExcess InvPE on a.LeaseID = InvPE.LeaseID WHERE a.TrancheNumber = '2' SELECT b.ScheduleNumber ,b.leaseID ,[Billed Months Under Upgrade] = b.[Billed Months] ,[Monthly Premium] = CASE WHEN a.Premium < 0 THEN 0 ELSE a.Premium END ,[Cumulative Premium] = CASE WHEN ((a.OldMasterLease-(DATEDIFF(MONTH,'2-29-16',c.FirstInvoiceUnderNewRent)-2)) * a.NewMonthlyRent)-(((a.OldMasterLease-(DATEDIFF(MONTH,'2-29- 16',c.FirstInvoiceUnderNewRent)-1)) * a.OldMonthlyRent) + a.OldLeaseFinalRent) < 0 THEN 0
  • 7. ELSE ((a.OldMasterLease-(DATEDIFF(MONTH,'2-29-16',c.FirstInvoiceUnderNewRent)-2)) * a.NewMonthlyRent)-(((a.OldMasterLease-(DATEDIFF(MONTH,'2-29- 16',c.FirstInvoiceUnderNewRent)-1)) * a.OldMonthlyRent) + a.OldLeaseFinalRent) END INTO #CumulativePremiums FROM #CombinedOldNew_Upgrades a INNER JOIN #LeaseLevelDetail b ON a.newleaseID = b.leaseID INNER JOIN #UpgradedLeases c ON a.NewLeaseID = c.LeaseID WHERE b.[upgrade IND] = 1 SELECT [ScheduleNumber] ,[LeaseID] ,[DRV] = ISNULL(b.Residual_Value,0) INTO #MiscLeases FROM #LeaseLevelDetail a INNER JOIN #DRV2 b ON a.ScheduleNumber = b.LeaseScheduleNumber WHERE [Misc IND] = 1 SELECT a.ScheduleNumber ,[Standard Rent Billed] = SUM(ISNULL(a.[Standard Rent Billed],0)) ,[Remaining Residual Value] = SUM(ISNULL(a.[Remaining Residual Value],0)) ,[Monthly Premium] = SUM(ISNULL(B.[Monthly Premium],0)) ,[Cumulative Premium] = SUM(ISNULL(B.[Cumulative Premium],0)) ,[DRV of Misc Invoiced Leases] = SUM(ISNULL(c.[DRV],0)) ,[Total Accelerated Rent Invoiced] = SUM(ISNULL(a.[Total Accelerated Rent Invoiced],0)) ,[Total Accelerated Device Invoiced] = SUM(ISNULL(a.[Total Accelerated Device Invoiced],0)) INTO #5ColumnAddition FROM #LeaseLevelDetail a LEFT JOIN #CumulativePremiums b ON a.leaseID = b.leaseID LEFT JOIN #MiscLeases c ON a.leaseID = c.leaseID GROUP BY a.schedulenumber SELECT a.* ,b.[Standard Rent Billed] ,b.[Remaining Residual Value] ,b.[Monthly Premium] ,b.[Cumulative Premium] ,b.[DRV of Misc Invoiced Leases] ,b.[Total Accelerated Rent Invoiced] ,b.[Total Accelerated Device Invoiced] FROM #FinalDynamicTranche a INNER JOIN #5ColumnAddition b ON a.[MasterLease Schedule Number] = b.ScheduleNumber