需要用以前的值替换NULL

时间:2020-07-31 11:07:39

标签: mysql coalesce

有必要联接表,但是要使最后的已知值代替NULL值并相乘

我有2个表“ oper”和“ curs”

  1. oper-具有2列date(date),sum(int)
  2. curs-有2列“ date”(date),“ cur”(int) [1]:https://i.stack.imgur.com/Og8QY.png

我运行代码:

    SELECT  oper.date AS "Date", 
        oper.sum AS "SUM, USD",
        curs.cur AS "USD/RUB", 
        round(oper.sum * curs.cur,2) AS "SUM, RUB" 
FROM operations
LEFT JOIN currency ON oper.date = cur.date

我得到:

date       | sum.USD | USD/RUB | SUM.RUB
01.01.2020 | 3464    | 71,21   | 246671,44
02.01.2020 | 1091    | 67,99   | 74177,09
03.01.2020 | 2991    | 69,81   | 208801,71
04.01.2020 | 1919    | NULL    | NULL
05.01.2020 | 1560    | NULL    | NULL
06.01.2020 | 2479    | 70,5    | 174769,5
07.01.2020 | 2521    | NULL    | NULL
08.01.2020 | 3382    | NULL    | NULL
09.01.2020 | 3112    | 70,21   | 218493,52
10.01.2020 | 1632    | 69,9    | 114076,8

我想得到(最好在一个请求中使用COALESCE):

date       | sum.USD | USD/RUB | SUM.RUB
01.01.2020 | 3464    | 71,21   | 246671,44
02.01.2020 | 1091    | 67,99   | 74177,09
03.01.2020 | 2991    | 69,81   | 208801,71
04.01.2020 | 1919    | 69,81   | 133965,39
05.01.2020 | 1560    | 69,81   | 108903,6
06.01.2020 | 2479    | 70,5    | 174769,5
07.01.2020 | 2521    | 70,5    | 177730,5
08.01.2020 | 3382    | 70,5    | 238431
09.01.2020 | 3112    | 70,21   | 218493,52
10.01.2020 | 1632    | 69,9    | 114076,8

1 个答案:

答案 0 :(得分:1)

在MySQL 8+上,我们可以在此处使用LAST_VALUE分析函数:

SELECT
    oper.date AS "Date", 
    oper.sum AS "SUM, USD",
    LAST_VALUE(curs.cur IGNORE NULLS) OVER (ORDER BY oper.date) AS "USD/RUB", 
    ROUND(oper.sum *
          LAST_VALUE(curs.cur IGNORE NULLS) OVER (ORDER BY oper.date), 2) AS "SUM, RUB" 
FROM operations oper
LEFT JOIN currency curs
    ON oper.rep_date = curs.date;

在早期版本的MySQL上,我们可以尝试使用相关子查询来填补空白:

SELECT
    oper.date AS "Date", 
    oper.sum AS "SUM, USD",
    (SELECT curs.cur FROM currency curs
     WHERE curs.date <= oper.date AND curs.cur IS NOT NULL
     ORDER BY curs.date DESC LIMIT 1) "USD/RUB", 
    ROUND(oper.sum *
          (SELECT curs.cur FROM currency curs
           WHERE curs.date <= oper.date AND curs.cur IS NOT NULL
           ORDER BY curs.date DESC LIMIT 1), 2) AS "SUM, RUB" 
FROM operations oper
ORDER BY date;
相关问题