选择最近的行 - 过去24小时

时间:2018-05-31 01:07:20

标签: sql postgresql

我有一个看起来像这样的表:

col1  | col2 | col3 | t_insert
---------------------------------
 1    | z     |     |2018-04-25 17:23:46.686816+10
 1    | zy    |     |2018-04-26 18:53:46.686816+10
 2    | f     |     |2018-04-26 19:23:46.686816+10
 3    | g     |     |2018-04-27 17:23:46.686816+10
 2    | z     |     |2018-04-27 18:23:46.686816+10   
 4    | z     |     |2018-04-27 20:13:46.686816+10

如果col1中有重复值,我想按最近的时间戳选择并创建一个新列(col4)并插入字符串'update'。

如果col1中没有重复值,我想选择值并将字符串'new'插入col4。

此外,我只想选择过去24小时内有时间戳的行。

预期结果:(此结果不显示过去24小时内的选定行数)

col1  | col2 | col3 | t_insert                     | col4   |
-------------------------------------------------------------
 1    | zy    |     |2018-04-26 18:53:46.686816+10 |update  |
 3    | g     |     |2018-04-27 17:23:46.686816+10 |new     |
 2    | z     |     |2018-04-27 18:23:46.686816+10 |update  | 
 4    | z     |     |2018-04-27 20:13:46.686816+10 |new     |

提前致谢,

1 个答案:

答案 0 :(得分:0)

嗯,窗口功能可以帮到这里:

select col, col2, col3, t_insert,
       (case when cnt > 1 then 'update' else 'new' end) as col4
from (select t.*,
             count(*) over (partition by col1) as cnt,
             row_number() over (partition by col1 order by t_insert desc) as seqnum
      from t
      where t_insert >= now() - interval '24 hour'
     ) t
where seqnum = 1;