PostgreSQL窗口函数

考虑以下表结构:
CREATE TABLE tb_log
(
  id INTEGER PRIMARY KEY,moment DATE,old INTEGER,actual INTEGER
);

包含数据:

INSERT INTO
  tb_log ( id,moment,old,actual )
VALUES
  ( 1,'2018-06-19',10,20 ),( 2,'2018-06-21',20,30 ),( 3,'2018-06-25',30,40 );

我试图从tb_log获取一个值生效的期间(开始日期和结束日期).

试验#1 – 使用lag()函数

SELECT
  lag( moment ) OVER (ORDER BY moment) date_start,moment AS date_end,old AS period_value
FROM
   tb_log;

返回以下数据:

| date_start |   date_end | period_value |
|------------|------------|--------------|
|     (null) | 2018-06-19 |           10 |
| 2018-06-19 | 2018-06-21 |           20 |
| 2018-06-21 | 2018-06-25 |           30 |

试验#2 – 使用lead()函数

SELECT
  moment AS date_start,lead( moment ) OVER (ORDER BY moment) date_end,actual AS period_value
FROM
   tb_log;

返回以下数据:

| date_start |   date_end | period_value |
|------------|------------|--------------|
| 2018-06-19 | 2018-06-21 |           20 |
| 2018-06-21 | 2018-06-25 |           30 |
| 2018-06-25 |     (null) |           40 |

SQLFiddle.com

有没有使用Window Functions返回这样的东西的技巧:

| date_start |   date_end | period_value |
|------------|------------|--------------|
|     (null) | 2018-06-19 |           10 |
| 2018-06-19 | 2018-06-21 |           20 |
| 2018-06-21 | 2018-06-25 |           30 |
| 2018-06-25 |     (null) |           40 |

有任何想法吗?

使用窗口函数没有技巧,因为窗口函数不会向数据添加行.使用lead()更自然(在我看来):
(SELECT moment,lead(moment) over (order by moment) as date_end,actual AS period_value
 FROM tb_log
)
UNION ALL
(SELECT null,old
 FROM tb_log
 ORDER BY moment
 LIMIT 1
);

一般来说,使用union all而不是union是一个好主意.联盟会产生删除重复项的开销.

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...