[英]Select column from another table based on matching condition
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)我想 select TABLE1 的所有列和一个附加列
Limit_At_Time
,它是具有最近日期的行的 TABLE2 的Limit
列的值(相对于 TABLE1.Date)
TABLE1:表格1:
Customer_ID Date Amount
1 01/01/2019 5
2 02/05/2019 15
TABLE2:表 2:
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:我得到的最接近的是使用此查询选择
previous_date
列:
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
.这从 TABLE2 中获取了我对每个 TABLE1 行感兴趣的事件日期,但我需要提取包含该
previous_date
的行的Limit
列值。
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
:您可以将子查询用作
table1
和table2
之间的JOIN
条件,然后您可以从table2
获取Limit
值:
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: 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 <
.当然,与您的查询完全等价的是
<
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.