【问题标题】:Join Tables with date range [closed]加入日期范围的表[关闭]
【发布时间】:2020-04-20 15:37:59
【问题描述】:

我有 2 个要加入的表。但也增加了日期范围。我怎样才能做到这一点?

提前致谢

【问题讨论】:

  • 数据库是什么?
  • 这里的大多数人都希望样本表数据和预期结果为格式化文本,而不是图像。

标签: sql date join group-by


【解决方案1】:

一个合理的选择是相关子查询:

select 
    t1.*,
    (
        select sum(t2.new_users)
        from table_2
        where 
            t2.campaignid = t1.campaignid 
            and t2.date between t1.sentdate and t1.enddate
    ) new_users
from table_1 t1

【讨论】:

    【解决方案2】:

    加入和聚合就可以了:

    select
      a.sentdate, a.enddate, a.campaignid, a.sent,
      sum(b.New_Users) as New_Users
    from table1 a
    join table2 b on b.date >= a.sentdate and b.date <= a.enddate
                 and b.campaignid = a.campaignid
    group by a.sentdate, a.enddate, a.campaignid, a.sent
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-23
      • 2021-02-10
      • 2017-04-27
      • 2011-01-19
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      相关资源
      最近更新 更多