Question

I need to generate a diagram out of data from a table. This table has the following date:

Timestamp | Value
01-20-2013| 5
01-21-2013| 7
01-22-2013| 3
01-25-2013| 5

As you can see not every date has a value. If I put that into a diagram it looks weird. Dates are used for the X-axis. As 01-23-2013 and 01-24-2013 is missing this values are either not printed in the diagram (looks weird) or the are printed put the line of the diagram goes from 3 directly to 5 and not to 0 as it should.

Is there a way via SQL to select the data so that it looks like this:

Timestamp | Value
01-20-2013| 5
01-21-2013| 7
01-22-2013| 3
01-23-2013| 0
01-24-2013| 0
01-25-2013| 5

Any help is appreciated!

Regards, Alex

Edit: I had no clue that the database engine was that important. This is running on a MySQL 5 Database (not sure about the complete version string).

Was it helpful?

Solution

There are various ways to do this, depending on the database. Date functions are notoriously database independent.

Here is an approach using a "driver" table with all dates and to use this for a left outer join:

select driver.timestamp, coalesce(t.value, 0) as value
from (select distinct timestamp + n.n as timestamp
      from t cross join
           (select 0 as n union all select 1 union all select 2 union all select 3
           )
     ) driver left outer join
     t;

This version assumes that there are gaps of no more than three days.

In some databases, you can construct the list of dates using a recursive CTE. Such an approach would handle gaps of any size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top