Joining tables that compute values between dates

前端 未结 2 441
暗喜
暗喜 2021-01-25 13:40

so I have the two following tables

Table A

Date        num
01-16-15    10
02-20-15    12
03-20-15    13

Table B

Date           


        
2条回答
  •  清酒与你
    2021-01-25 14:25

    Hmmm. In standard SQL you can do:

    select b.*,
           (select a.num
            from a
            where a.date <= b.date
            order by a.date desc
            fetch first 1 row only
           ) * value as new_value
    from b;
    

    I don't think this meets the range conditions, but I don't understand your description of that.

    I also don't know if Impala supports correlated subqueries. An alternative is probably faster on complex data:

    with ab as (
          select a.date, a.value as a_value, null as b_value, 'a' as which
          from a
          union all
          select b.date, null as a_value, b_value, 'b' as which
          from b
         )
    select date, b_value * a_real_value
    from (select ab.*,
                 max(a_value) over (partition by a_date) as a_real_value
          from (select ab.*,
                       max(a.date) over (order by date, which) as a_date
                from ab
               ) ab
         ) ab
    where which = 'b';
    

提交回复
热议问题