Dav*_*idJ 5 sql time-series data-warehouse data-cleaning
在格式化数据以进行时间序列分析时,通常需要通过随时间推移填充前馈值(也称为Last-Observation-Carried-Forward / LOCF)来估算缺失值。
尽管数据分析环境通常提供该功能(例如Pandas fillna()),但对于较大的数据集,在SQL中进行计算(例如,利用数据并行数据仓库设备)可能会更加高效。
例如,考虑:
| UNIT | TIME | VALUE |
|------|------|-------|
| 1 | 1 | NULL |
| 1 | 2 | .5 |
| 1 | 3 | NULL |
| 1 | 4 | NULL |
| 1 | 5 | .2 |
| 1 | 6 | NULL |
| 2 | 1 | .6 |
| 2 | 2 | NULL |
Run Code Online (Sandbox Code Playgroud)
在TIME之前填充VALUE列后(对于每个UNIT独立),结果如下:
| UNIT | TIME | VALUE |
|------|------|-------|
| 1 | 1 | NULL |
| 1 | 2 | .5 |
| 1 | 3 | .5 |
| 1 | 4 | .5 |
| 1 | 5 | .2 |
| 1 | 6 | .2 |
| 2 | 1 | .6 |
| 2 | 2 | .6 |
Run Code Online (Sandbox Code Playgroud)
(请注意,由于没有先验值,因此无法估算UNIT 1的初始NULL)
时间也可以是时间戳记或日期时间类型列。
对于某些数据库,例如 Postgres,您可以定义自己的聚合函数。LOCF 只是一个正在运行的 COALESCE。
CREATE OR REPLACE FUNCTION locf_state( FLOAT, FLOAT )
RETURNS FLOAT
LANGUAGE SQL
AS $f$
SELECT COALESCE($2,$1)
$f$;
CREATE AGGREGATE locf(FLOAT) (
SFUNC = locf_state,
STYPE = FLOAT
);
Run Code Online (Sandbox Code Playgroud)
这样查询就更具可读性:
SELECT unit, time,
locf(value) OVER( PARTITION BY unit ORDER BY time )
FROM mytable;
Run Code Online (Sandbox Code Playgroud)
SQLFiddle: http: //sqlfiddle.com/#!15/2c73b/ 1/0
如果使用 PostgreSQL 风格的 SQL 方言(例如 Netezza PureData)作为日期时间索引(假设过去的数据),以下查询结构将实现前向填充。它也适用于多列索引/键。
给定以下参数:
<key_cols>- 唯一标识每个时间序列样本的列列表(例如UNIT, TIME)<impute_col>- 需要估算值的列(例如VALUE)<impute_over_range_col>- 时间序列的连续范围列(例如TIME)并推导:
<keys_no_range>- 关键列,除了<impute_over_range_col>SELECT DISTINCT T1.<key_cols>,
COALESCE(T1.<impute_col>, T2.<impute_col>) AS <impute_col>
FROM table T1
LEFT OUTER JOIN (SELECT T1.<key_cols>,
T1.<impute_col>,
LEAD(T1.<impute_over_range_col>,1)
OVER (PARTITION BY T1.<keys_no_range>
ORDER BY T1.<key_cols>)
AS NEXT_RANGE
FROM table T1
WHERE T1.<impute_col> IS NOT NULL
ORDER BY T1.<key_cols>
) T2
ON (T1.<impute_over_range_col> BETWEEN T2.<impute_over_range_col>
AND COALESCE(NEXT_RANGE, CURRENT_DATE))
AND T1.<keys_no_range>[0] = T2.<keys_no_range>[0]
AND T1.<keys_no_range>[1] = T2.<keys_no_range>[1]
-- ... for each col in <keys_no_range>
Run Code Online (Sandbox Code Playgroud)
具体来说,对于问题中的例子:
SELECT DISTINCT T1.UNIT, T1.TIME,
COALESCE(T1.VALUE, T2.VALUE) AS VALUE
FROM table T1
LEFT OUTER JOIN (SELECT T1.UNIT, T1.TIME,
T1.VALUE,
LEAD(T1.TIME,1)
OVER (PARTITION BY T1.UNIT
ORDER BY T1.UNIT, T1.TIME)
AS NEXT_RANGE
FROM table T1
WHERE T1.VALUE IS NOT NULL
ORDER BY T1.UNIT, T1.TIME
) T2
ON (T1.TIME BETWEEN T2.TIME
AND COALESCE(NEXT_RANGE, CURRENT_DATE))
AND T1.UNIT = T2.UNIT
Run Code Online (Sandbox Code Playgroud)
这是上述查询的 SQLFiddle:http://sqlfiddle.com/#!15 /d589b/1