Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In MySQL 5.7 I am trying to retrieve price data from a table for each day. The table contains only price changes.

DATE       | SKU | PRICE
2020-01-15   123   4.99
2020-01-10   123   3.99

If no change has occured on a particular day, we can assume the price has stayed the same. My objective is to create a graf in grafana displaying the price over time.

The desired output is therefore:

DATE       | SKU | PRICE
2020-01-15   123   4.99
2020-01-14   123   3.99
2020-01-13   123   3.99
2020-01-12   123   3.99
2020-01-11   123   3.99
2020-01-10   123   3.99

After some investigation I create a stored procedure that joins against a tmp table with dates:

delimiter //
create
    definer = root@localhost procedure sp1(IN d1 date, IN d2 date)
BEGIN
  declare d datetime;

  create temporary table if not exists foo (d date not null);

  set d = d1;
  while d <= d2 do
    insert into foo (d) values (d);
    set d = date_add(d, interval 1 day);
  end while;

  select
    foo.d,
    p.*
  from foo
    left join prices_test2 p on foo.d = p.date
  order by
    foo.d asc;

  drop temporary table foo;

END//

Then simply call it like this:

call sp1(210110, 210122)

Now the issue is, that this procedure returns NULL for any date without price but it should return the last known price for the SKU.

How can this be achieved?

question from:https://stackoverflow.com/questions/65841804/return-values-for-a-time-series-with-last-known-value-for-each-day-in-mysql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...