PostgreSQL 取前一列不为 NULL
PostgreSQL 取前一列不为 NULL 的值
案例:假设有如下一个表,其结构和数据如下。根据需求写出对应的 SQL。
date lv income
2021-01-01 1.1 100
2021-01-02 1.2 300
2021-01-03 1.3 301
2021-01-05 303
2021-01-06 1.8 304
2021-01-07 1.9 305
2021-01-04 302
需求:当 lv 为 NULL 时,取 date 小于当前 date 的 lv 不为 NULL 的 date 的 lv
解法1:
SELECT date,
lv,
income,
CASE WHEN lv IS NOT NULL THEN lv ELSE(SELECT a.lv FROM tmp AS a WHERE a.date < b.date AND a.lv IS NOT NULL ORDER BY a.date DESC LIMIT 1) END AS lv
FROM tmp AS b
ORDER BY b.date;
解法2:
SELECT date,
lv,
income,
first_value(lv) over (partition by lvs order by date)
FROM (
SELECT date,
lv,
income,
SUM(CASE WHEN lv IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY date) AS lvs
FROM tmp
ORDER BY date ASC ) AS b;
解法一的思路非常的巧妙,并且 SQL 的执行效率也不会很差。