[英]mysql join on date where one table's date is a month before
I have 2 tables of which I want to join on the date. 我要在该日期加入2个表。 While the date are of the same format, I want to join t1.date_1
to t2.date_2
but where t2.date_2
is a month before. 虽然日期相同的格式,我想加入t1.date_1
到t2.date_2
但如果t2.date_2
是一个月前。 Please see my query below for context and the output I want: 请在下面查看我的查询以获取上下文和所需的输出:
t1
date_1 count_t1
2015-01-01 10
2015-02-01 20
2015-03-01 30
t2
date_2 count_t2
2014-12-01 40
2015-01-01 50
2015-02-01 60
2015-03-01 70
output i want:
date_1 percent_before
2015-01-01 0.25 <--10/40
2015-02-01 0.40 <--20/50
2015-03-01 0.5 <--30/60
my query:
select (t1.count_1/t2.count_2) as percent_before
from table1 t1 join table2 t2
on t1.date_1 = (t2.date_2 - 1 month);
You need the interval
keyword: 您需要interval
关键字:
select t1.date_1, (t1.count_1 / t2.count_2) as percent_before
from table1 t1 join
table2 t2
on t1.date_1 = (t2.date_2 - interval 1 month);
For people using teradata and cannot use interval: 对于使用Teradata但不能使用间隔的人:
select t1.date_1, (t1.count_1 / t2.count_2) as percent_before
from table1 t1 join
table2 t2
on t1.date_1 = add_months(t2.date_2 - 1 month);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.