DECLARE @Customers table(id int, CustName varchar(100), ReferredBy varchar(100));
INSERT @Customers ( id, CustName, ReferredBy )
VALUES ( 0, 'Bob', 'Unknown' )
, ( 1, 'Ted', 'Bob' )
, ( 2, 'Carol', 'Ted' )
, ( 3, 'Alice', 'Carol' )
, ( 4, 'Jeb', 'George' )
, ( 5, 'Eddie', 'Ella' );
DECLARE @Invoices table(id int IDENTITY, Billingdate date, customerid int);
INSERT @Invoices ( Billingdate, customerid )
VALUES ( '20180117', 5 )
, ( '20180122', 2 )
, ( '20180227', 4 )
, ( '20180228', 1 )
, ( '20180314', 0 )
, ( '20180422', 3 )
, ( '20180518', 2 )
, ( '20180312', 5 )
, ( '20180213', 4 )
, ( '20180104', 0 )
, ( '20180311', 1 )
, ( '20180601', 2 )
, ( '20180617', 4 )
, ( '20180119', 3 )
, ( '20180508', 1 )
, ( '20180425', 2 )
, ( '20180418', 5 );
WITH MostRecent AS
(SELECT c.CustName
, c.ReferredBy
, i.id InvoiceNum
, i.BillingDate
, Row_Number() OVER (ORDER BY i.Billingdate DESC) rn
FROM @Customers c
JOIN @Invoices i ON c.id = i.customerid)
SELECT
MostRecent.CustName
, MostRecent.ReferredBy
, MostRecent.InvoiceNum
, MostRecent.Billingdate
FROM MostRecent
WHERE MostRecent.rn = 1;
WITH SecondMostRecent AS
(SELECT c.CustName
, c.ReferredBy
, i.id InvoiceNum
, i.BillingDate
, Row_Number() OVER (ORDER BY i.Billingdate DESC) rn
FROM @Customers c
JOIN @Invoices i ON c.id = i.customerid)
SELECT
SecondMostRecent.CustName
, SecondMostRecent.ReferredBy
, SecondMostRecent.InvoiceNum
, SecondMostRecent.Billingdate
FROM SecondMostRecent
WHERE SecondMostRecent.rn = 2;
