I'm trying to join two tables in SQL server, but I'm not getting the expected result. I've one table which I joined on itself to get the value for the latest timestamp for each ID reading. This I managed by following:
SELECT a.[ID_A], a.[ID_B], a.[VALUE], a.[TIMESTAMP]
FROM TABLE_NAME a
INNER JOIN (
SELECT [ID_A], max([TIMESTAMP]) as LATEST_TIMESTAMP
FROM TABLE _NAME
GROUP BY [ID_A]
) b
ON a.[ID_A] = b.[ID_A]
I now want to join it to another table, which also contains ID_A. It's not necessary to keep any variable from this table, I only want to use this table to filter the previous selection (so, the output of the code should be filtered to contain only ID's which are included in the second table. I thought it was as easy as
SELECT a.[ID_A], a.[ID_B], a.[VALUE], a.[TIMESTAMP]
FROM TABLE_1 a
INNER JOIN (
SELECT [ID_A], max([TIMESTAMP]) as LATEST_TIMESTAMP
FROM TABLE_1
GROUP BY [ID_A]
) b
ON a.[ID_A] = b.[ID_A]
RIGHT JOIN TABLE_2 c
ON c.[ID_A] = a.[ID_A]
But this gives me a table where ID_A has several lines, and has multiple values and timestamps (so not only the the latest one), even though the first part of the code does return only the latest value if I run it seperatly.
Anyone an idea on how to achieve this?