将NULL替换为上一个和下一个记录的平均值

时间:2014-03-17 06:36:42

标签: sql replace null calculated-columns

(新手在Access工作)。

我有一些数据是每小时给出的PV输出功率。 每半小时数据都有一个空单元格,我想创建一个列,其中包含空的X.30 pm记录中Xpm和Ypm值的平均值。

INPUT DATA((PV_KW):我的数据如下所示:

1pm,    30kW;
1.30pm, NULL;
2pm,    40kW;
2.30pm  NULL;
3pm,    60kW;

期望的输出:我希望这成为

1pm,    30kW;
1.30pm, 35kW;
2pm,    40kW;
2.30pm, 50KW;
3pm,    60kW;

我写的查询确实平均没问题,但输出列(PV_KW_AVG)只包含平均值并用NULL替换原始数据...即得到这个:

1pm,    NULL;
1.30pm, 35kW;
2pm,    NULL;
2.30pm, 50KW;
3pm,    NULL;

这是我的疑问:

    SELECT 

    (
    (SELECT last(PV_kw)
       FROM PV_and_load AS temp
      WHERE PV_and_load.id =(temp.id+1) 
            AND temp.PV_kw IS NOT NULL)
    +
    (SELECT last(PV_kw)
       FROM PV_and_load AS temp2
      WHERE PV_and_load.id = (temp2.id-1) 
            AND temp2.PV_kw IS NOT NULL)
    )
    /2

AS PV_KW_avg, *
FROM PV_and_load;

任何人都可以告诉我如何将输出输出到我想要的输出 - 即计算平均值并保留原始数据吗?

1 个答案:

答案 0 :(得分:0)

如果您的查询工作正常,那么您可以执行以下操作:

SELECT ID,CASE WHEN PV_kw IS NOT NULL THEN PV_kw ELSE PV_KW_avg AS PV_KW FROM
(SELECT
(
(SELECT last(PV_kw)
   FROM PV_and_load AS temp
  WHERE PV_and_load.id =(temp.id+1) 
        AND temp.PV_kw IS NOT NULL)
+
(SELECT last(PV_kw)
   FROM PV_and_load AS temp2
  WHERE PV_and_load.id = (temp2.id-1) 
        AND temp2.PV_kw IS NOT NULL)
)
/2
AS PV_KW_avg, *
FROM PV_and_load) tab;