Use most recent date for missing dates when joining tables

后端 未结 2 1956
萌比男神i
萌比男神i 2021-01-17 03:51

I have 2 tables:

1.tran_test : (id, amount, currency(Currency_Name), date_1)
2.cur_test: (id, currency, date_2, price(amount In USD))

How t

相关标签:
2条回答
  • 2021-01-17 04:13
    select date_1, SUM(amount*c.price) AS sum_by_day
    from
    (
        select *, max (date_2) as lastDate
        from tran_test AS t
        INNER JOIN cur_test AS c
        ON t.currency = c.currency AND date_1 >= date_2
        GROUP BY date_1;
    ) as t
    INNER JOIN cur_test AS c
    ON t.currency = c.currency AND lastdate = date_2
    GROUP BY date_1;
    
    0 讨论(0)
  • 2021-01-17 04:18

    Write a subquery that finds the most recent date in the currency table for each date in the transaction table.

    SELECT t.date_1, MAX(c.date_2) AS latest_date
    FROM tran_test AS t
    JOIN cur_test AS c ON t.date_1 >= c.date_2
    GROUP BY t.date1
    

    You can then join this with the rest of your query.

    SELECT t.date_1, SUM(t.amount * c.price) AS sum_by_day
    FROM tran_test AS t
    JOIN (
        SELECT t.date_1, MAX(c.date_2) AS latest_date
        FROM tran_test AS t
        JOIN cur_test AS c ON t.date_1 >= c.date_2
        GROUP BY t.date1) AS g ON g.date_1 = t.date_1
    JOIN cur_test AS c ON c.date_2 = g.latest_date
    GROUP BY t.date_1
    
    0 讨论(0)
提交回复
热议问题