2015-10-07 73 views
0

我试图从用户的初始日期到当前日期添加时间(小时分钟和秒),但我收到了错误。从一个时间戳字段添加时间到其他字段

我不知道我做错了,接受其他的建议

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' 

这个错误,我recevied

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', 
                              ^
+0

CURRENT_DATE-2?这是一个标识符名称,或者你是否试图从该领域中减去某些东西?此外,语法突出显示在提示错误信息方面做得很好,但仍应始终发布错误消息。 –

+0

嗨,我已经添加了错误,current_date - 2从current_date减少2天 – user3600910

回答

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; 
+0

我可以做到这一点与Windows功能,因为我有更多的字段在选择? – user3600910

+0

@ user3600910当然,最重要的部分是日期/时间操作,对吧?你应该能够找出其他问题。 –

+0

我试图改变它,但它不起作用 – user3600910

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; 

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

+0

我需要的是添加时间current_date -2为什么我使用to_chat – user3600910

+0

@ user3600910我更正了我的答案 - 如果毫秒毫无用处,您只需将'timestamp'施加到'time'或使用'date_trunc(text,timestamp)'' –