I have two tables that have time-series data in the following form. I want to select all of the columns of TABLE1 and an additional column Limit_At_Time
which is the value of the Limit
column of TABLE2 for the row which has the most recent Date (relative to TABLE1.Date)
TABLE1:
Customer_ID Date Amount
1 01/01/2019 5
2 02/05/2019 15
TABLE2:
Customer_ID Date Limit
1 12/05/2018 10
1 12/25/2018 20
2 01/05/2019 30
2 03/08/2019 50
Result:
Customer_ID Date Amount Limit_At_Time
1 01/01/2019 5 20
2 02/05/2019 15 30
The closest I have gotten is selecting a previous_date
column with this query:
SELECT *,
(SELECT MAX(Date) FROM TABLE2 t2
WHERE t2.Date < t1.Date
AND t2.Customer_ID = t1.Customer_ID)
as previous_date
FROM TABLE1 AS t1
This gets me the date of the event from TABLE2 that I am interested in for each TABLE1 row, but I need to extract the Limit
column value of the row that contains that previous_date
.
How can I achieve the result that I want?
You can use your subquery as a JOIN
condition between table1
and table2
which will then allow you to get the Limit
value from table2
:
SELECT t1.Customer_ID, t1.Date, t1.Amount, t2.Limit
FROM table1 t1
JOIN table2 t2 ON t2.Customer_ID = t1.Customer_ID
AND t2.Date = (SELECT MAX(Date) FROM table2 t2b
WHERE t2b.Date < t1.Date
AND t2b.Customer_ID = t1.Customer_ID)
Output:
Customer_ID Date Amount Limit
1 2019-01-01 5 20
2 2019-02-05 15 30
I would just use a correlated subquery:
select t1.*,
(select t2.limit
from table2 t2
where t2.date <= t1.date
order by t2.date desc
limit 1
) as Limit_At_Time
from table1 t1;
Usually in these types of problems, the comparison is <=
rather than <
, so I used that. Of course, the exact equivalent to your query is <
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.