将时间从一个时间戳字段添加到其他字段

时间:2015-10-07 11:56:38

标签: postgresql amazon-redshift window-functions

我正在尝试将用户初始日期的时间(小时分和秒)添加到当前日期,但收到错误。

我不知道我做错了什么,对其他建议持开放态度

select distinct uid,
       min (ts) over (partition by uid order by ts rows unbounded preceding) as initial_date,
       current_date-2 + interval 'to_char(min (ts) over (partition by uid order by ts rows unbounded preceding),'HH') hours'
  from mr_session_log
where ts >= '2015-09-01'

这就是我收到的错误

ERROR: syntax error at or near "') hours'"

职位:355

current_date-2 + interval 'to_char(min (ts) over (partition by uid order by ts rows unbounded preceding),'HH') hours',
                                                                                                               ^

2 个答案:

答案 0 :(得分:0)

你不应该过度设计解决方案,语法高亮显示你不能把函数放在间隔中,当你想要uid和uid分区时,不需要窗口函数。

SELECT uid, (current_date -2 ) + min(ts::time)
FROM mr_session_log
WHERE ts >= '2015-09-01'
GROUP BY uid
ORDER BY uid;

答案 1 :(得分:0)

如果你真的需要使用窗口功能,它也很简单:

SELECT DISTINCT
    uid,
    CURRENT_DATE - 2 - MIN(ts::time) OVER (PARTITION BY uid
                                     ORDER BY ts
                                     ROWS UNBOUNDED PRECEDING) AS date_with_added_time
FROM mr_session_log
WHERE ts >= '2015-09-01'::DATE;

如果您只需要小时,分钟和秒,请使用MIN(date_trunc('secconds', ts)::time)代替MIN(ts::time)