0

I have data as below, which is partial and few rows are missing. I need an average with data considering the previous available value. Do we have any function available for such an average in sql? 

Needed average: 220 

Available data for 10 days:

1st day: 100
4th day: 200
7th day: 300
10th day: 400

Putting the same in a table format:

Rows    Date        Partial Continuous(needed)
1       01-Aug-18   100     100     
2                           100
3                           100
4       04-Aug-18   200     200     
5                           200
6                           200
7       07-Aug-18   300     300     
8                           300
9                           300
10      10-Aug-18   400     400     
-----------------------------------
Average             250     220
-----------------------------------

I am looking at something like select avg(partial*(nextdate-date))/(lastdate-firstdate) from mytable;

Anu
  • 176
  • 1
  • 3
  • 14

2 Answers2

0

Use a user-defined variable to fill in the missing values.

SELECT AVG(normal)
FROM (SELECT IFNULL(continuous, @prev) AS normal, @prev := IF(continuous IS NULL, @prev, continuous)
      FROM (SELECT continuous
            FROM yourTable
            ORDER BY id) AS x
      CROSS JOIN (SELECT @prev := NULL) AS y
) as z
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

What about AVG()?

> SELECT AVG(Normal) FROM table WHERE something;
keithpjolley
  • 2,089
  • 1
  • 17
  • 20
  • 2
    I don't think the `normal` column really exists, he's just showing that he wants the rows with missing values to inherit the value from the previous line. – Barmar Aug 09 '18 at 01:54
  • ah - I was wondering if maybe if Anu was calculating `Average` some strange way because with the numbers given the Average of `Normal` (and `Continuous`) is 220, not 250. – keithpjolley Aug 09 '18 at 02:02
  • @ keithpjolley : fixed the data. maybe it was scrambled while someone edited it. – Anu Aug 09 '18 at 13:26