Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

grafana - Return values for a time series with last known value for each day in MySQL

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...