【问题标题】:SQL need to join tables and return values with conditionsSQL需要连接表和返回值的条件
【发布时间】:2019-12-21 07:07:37
【问题描述】:

我有两个表需要加入和聚合。

表 1 每个日期和车辆有 1 行 表 2 每个日期和车辆可以有多行

我想加入日期和车辆,并检索大于 table1.max_job_complete_date 的 min(table2.end_times)。所需的值不一定是 table2 的最大 end_times,所以我不能简单地在分区上使用 row_number() ...

simplified visual of the two tables

我尝试了以下方法,但这并不一定会专门为该日期和驱动程序拉最大 end_time。

select
a."date",
a.vehicle,
a.max_job_complete_date,
from table1 as a
left join table2 as b
on b."date" = a."date"
and b.vehicle = a.vehicle
where b.end_times >= (select(max_load_complete_time from table1))

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。您只是从left join 的第一个表中选择列,因此似乎根本没有使用b

标签: sql date join multiple-conditions


【解决方案1】:
select
a."date",
a.vehicle,
a.max_job_complete_date,
min(b.end_time)
from table1 as a
left join table2 as b
on b."date" = a."date"
and b.vehicle = a.vehicle
Group by
a."date",
a.vehicle,
a.max_job_complete_date
Having b.end_time>a.max_job_complete_date

【讨论】:

    【解决方案2】:

    关联子查询可能是最简单的解决方案:

    select a.*,
           (select min(b.date)
            from table2 b
            where b.vehicle = a.vehicle and
                  b."date" = a."date" and
                  b.end_time >= a.max_load_complete_time
           ) as next_b_date
    from table1 a;
    

    【讨论】:

    • 谢谢,这正是我希望/需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多