加入表格时使用最新日期作为缺失日期

时间:2019-01-24 11:48:11

标签: mysql

我有2张桌子:

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

考虑到cur.test表中的某些日期缺失,如何获取每天的总销售总额,因此您需要使用最近可用的日期来计算结果?

我写了一个查询来计算总和,但不包括缺少费率的日子。

如何计算缺失天数?

SELECT date_1, SUM(amount*c.price) AS sum_by_day
 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;

我不需要只生成日期。我需要使用表格中可用的数据来计算金额。如果缺少某些日期,则在可以使用货币汇率时,我需要取最后一个可用的日期。例如-表格tran.test有一笔9月28日的交易,但是没有提供这一天的货币汇率,因此我需要采用最近的汇率

相似数据的样本

INSERT INTO tran_test (amount, currency, date_1) VALUES 
(1000,'RUB','2018-09-01'),
(15,'USD','2018-09-01'),
(10,'EUR','2018-09-01'),

INSERT INTO cur_test (name,date_2, price) VALUES
('RUB','2018-01-09',0.02),
('USD','2018-01-09',1),

输出应该像 日期-该日期的总金额 2018-02-21-2128

完整代码在这里-https://www.db-fiddle.com/f/v4SHW9XgtgyehbhanQFRx5/2 实际数据稍微复杂一点,并且包括UNIX格式的日期

2 个答案:

答案 0 :(得分:0)

编写一个子查询,以查找货币表中交易表中每个日期的最新日期。

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

然后您可以将其与其余查询一起加入。

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

答案 1 :(得分:0)

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;