SQL - Subtract OLDEST record in TABLE 2 from NEWEST record from TABLE 1 (Without Cursor)

The best way I can explain my question is with the graphic below.

I want to select the OLDEST record from TABLE 2 and the LATEST record from TABLE 1 and find the difference in a query. Obviously I can loop through my items and select TOP 1 from both tables and do the calculation, but as usual, this takes too long.

EE-Question1.jpg
IT GuyDir of ITAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
is that homework?

That query would do it:
DECLARE @current TABLE (Item VARCHAR(20),Date DATETIME, Value INT)
DECLARE @history TABLE (Item VARCHAR(20),Date DATETIME, Value INT)

INSERT INTO @history ( Item, Date, Value )
VALUES 
  ( 'Phone', '2018-05-10', 96 )
, ( 'Phone', '2018-05-11', 45 )
, ( 'Phone', '2018-05-12', 84 )
, ( 'Phone', '2018-05-13', 32 )
, ( 'Desk', '2018-05-14', 78 )
, ( 'Desk', '2018-05-15', 51 )
, ( 'Desk', '2018-05-16', 23 )

INSERT INTO @current ( Item, Date, Value )
VALUES 
  ( 'Phone', '2018-06-01', 85 )
, ( 'Phone', '2018-06-02', 62 )
, ( 'Phone', '2018-06-03', 33 )
, ( 'Desk', '2018-06-13', 81 )
, ( 'Desk', '2018-06-14', 98 )
, ( 'Desk', '2018-06-15', 58 )
, ( 'Desk', '2018-06-16', 65 )

;
WITH Table2
AS (
	SELECT *, ROW_NUMBER() OVER(PARTITION BY Item ORDER BY Date ASC) AS RN FROM @current
)
,
Table1
AS (
	SELECT *, ROW_NUMBER() OVER(PARTITION BY Item ORDER BY Date DESC) AS RN FROM @history
)

SELECT *, T2.Value - T1.Value AS Difference 
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T2.Item = T1.Item
AND T2.RN = 1
WHERE T1.RN = 1

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
IT GuyDir of ITAuthor Commented:
Eric.

You have taught me something today. I didn't fully understand the WITH statement or the ROW_NUMBER function until today, and you taught me.

After a little fiddling around it worked, and I'm very grateful. Thank you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.