用于在Postgresql中选择最新非空值的窗口函数不起作用

时间:2018-03-13 14:55:42

标签: postgresql window-functions

我有一个像这样的简单数据集:

CREATE TABLE test (ts timestamp, email varchar, title varchar, hobby varchar);

insert into test values
('2017-01-01', 'me@me.com', 'blah', null),
('2017-01-02', 'me@me.com', null, 'expected hobby'),
('2017-01-03', 'me@me.com', 'expected title', null),
('2017-01-04', 'me@me.com', null, null);

我想使用窗口函数为每封电子邮件选择最新的非空值标题和爱好。这些是“预期的头衔”和“预期的爱好”。我正在尝试这个:

SELECT DISTINCT
    email,
    first_value(title) OVER (partition by email order by ts desc nulls last),
    first_value(hobby) OVER (partition by email order by ts desc nulls last)
from test

但它似乎不起作用。这是一个sql小提琴:http://sqlfiddle.com/#!17/6d681/2

知道为什么吗?

2 个答案:

答案 0 :(得分:0)

我使用case语句修复它以消除空值:

SELECT DISTINCT
    email,
    first_value(title) OVER (partition by email order by case when title is not null then ts end desc nulls last),
    first_value(hobby) OVER (partition by email order by case when hobby is not null then ts end desc nulls last),
from test

答案 1 :(得分:0)

您的订单无效,

$cookies.remove("userInfo");

因为ts没有空值, 类似的东西也应该起作用(作为你的解决方案)

 order by ts desc nulls last

null的concat结果为null,所以ts || null结果为null