Joining tables that compute values between dates

前端 未结 2 443
暗喜
暗喜 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:30

    This works on MariaDb (MySql) and it's pretty basic so hopefully it works on impala too.

    SELECT b.date, b.value * a.num
    FROM tableB b, tableA a
    WHERE b.date >= a.date
      AND (b.date < (SELECT MIN(c.date) FROM tableA c WHERE c.date > a.date)
           OR NOT EXISTS(SELECT c.date FROM tableA c WHERE c.date > a.date))
    

    The last NOT EXISTS... was needed to include dates after the last date in table A

    Update In the revised version of the question the date in B is never larger (after) the last date in A so then the query can be written as

    SELECT b.date, b.value * a.num
    FROM tableB b, tableA a
    WHERE b.date >= a.date
      AND b.date <= (SELECT MIN(c.date) FROM tableA c WHERE c.date > a.date)
    

提交回复
热议问题