【问题标题】:mysql join on date where one table's date is a month beforemysql 加入日期,其中一个表的日期是一个月前
【发布时间】:2015-07-13 18:28:31
【问题描述】:

我有 2 张桌子,我想在该日期加入其中。虽然日期格式相同,但我想将t1.date_1 加入t2.date_2,但t2.date_2 是一个月前。请参阅下面的查询以了解上下文和我想要的输出:

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);

【问题讨论】:

  • 我的错误:Invalid operation for DateTime or Interval. Error Code: 5407

标签: mysql sql join


【解决方案1】:

您需要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);

【讨论】:

    【解决方案2】:

    对于使用 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);
    

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      相关资源
      最近更新 更多