Skip to content
Advertisement

subquery fetching 2 columns

In Access database file, I have:

T1

id   Item    TransactionDate  
-----------------------------
1    TV      31/12/2017  

T2

id   Item   U_Price      FromDate      Type
--------------------------------------------
1    TV     12.1$        31/12/2018   Smart55
2    TV     15.3$        30/11/2019   Smart55
3    TV     11.2$        25/02/2020   Smart56
4    TV     21.1$        01/05/2016   Smart10

I need the resulting table to have 1 row (from T1) with the most relevant U_Price, in the example 21.1$ with the highest FromDate smaller than the TransactionDate

The question has been properly answered here but now I need to fetch Type also

Advertisement

Answer

Consider:

SELECT T1.*, Top1.* FROM T1 INNER JOIN (
      SELECT T2.* FROM T2
      WHERE ID IN (
          SELECT TOP 1 Dupe.ID FROM T2 AS Dupe INNER JOIN T1 
          ON Dupe.Item=T1.Item 
          WHERE Dupe.Item=T2.Item AND Dupe.FromDate<=T1.TransactionDate 
          ORDER BY Dupe.FromDate DESC)) AS Top1 
ON T1.Item = Top1.Item;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement