【问题标题】:Join row with MAX row in another table in Impala?在 Impala 的另一个表中加入具有 MAX 行的行?
【发布时间】:2016-03-21 00:17:05
【问题描述】:

我有一个简单的任务是在“客户”(父表)和“订单”表(子表)之间进行连接,其中子表的连接行具有最新(最大)订单日期值。如果 Impala 与您可以编写的任何 SQL 引擎一样:

select * from customer c
join `order` o on o.customer_id=c.id
and o.id=(
    select o2.id 
    from `order` o2 
    where o2.customer_id=c.id 
    order by o2.order_date 
    desc limit 1
);

显然 impala 是不同的,因为我只是收到以下错误:

Error while compiling statement: FAILED: ParseException line 4:1 cannot recognize input near 'select' 'o2' '.' in expression specification

我尝试将子查询之间的“and”替换为“where”,但没有帮助。

【问题讨论】:

    标签: sql impala


    【解决方案1】:

    您应该能够在from 子句中使用joinaggregation 来做到这一点:

    select c.*, o.*
    from customer c join
         `order` o
         on o.customer_id = c.id join
         (select customer_id, max(o2.order_date) as maxod
          from `order` o2
          group by customer_id
         ) oo
         on oo.customer_id = o.customer_id and oo.maxod = o.order_date;
    

    这假设最大订单日期只有一个订单。如果这不合理,那么也许您可以只使用max(id) 而不是max(order_date)。如果 id 是按顺序分配的,那么这将满足您的需求。

    你可以使用exists做你想做的事:

    select c.*, o.*
    from customer c join
         `order` o
         on o.customer_id = c.id
    where not exists (select 1
                      from `order` o2
                      where o2.customer_id = o.customer_id and
                            (o2.order_date > o.order_date or
                             (o2.order_date = o.order_date and o2.id > o.id)
                            )
                     );
    

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 2023-03-27
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多