我有一个在标准sql上运行良好的查询,但redshift有一些限制,不允许在内部select中引用外部查询信息的查询。
查询的基本思想是从上次客户发布响应时生成时间戳的差异。我有一个论坛的客户发布时间戳,我想知道他们发布的时间,自上次发布以来时间差异是什么。这是在sql中运行测试数据的查询,具有预期输出:http://sqlfiddle.com/#!9/04358/2
以下是查询:
SELECT
current.id,
current.datetime,
TIMESTAMPDIFF(minute, current.datetime, IFNULL(next.datetime,
current.datetime)) as diff
FROM
TestTable as current
LEFT JOIN
TestTable as next
on next.datetime = (select min(datetime) from TestTable
where datetime > current.datetime and id = current.id)
order by
current.id, current.datetime
在redshift中,由于不支持子查询模式,因此不起作用。有任何想法如何将其变成非参考子查询?
答案 0 :(得分:1)
您不需要派生表。使用窗口函数first_value
来获取id最后一次发布评论并将其用于减法。
SELECT
id,
datetime,
DATEDIFF(minute, datetime, first_value(datetime) over(partition by id order by datetime desc rows between unbounded preceding and unbounded following)) as diff
FROM TestTable
我不确定Redshift中的另一个函数内是否有窗函数。在那种情况下试试,
SELECT
id,
datetime,
DATEDIFF(minute, datetime, last_response_time) as diff
FROM (SELECT t.*,first_value(datetime) over(partition by id order by datetime desc rows between unbounded preceding and unbounded following) as last_response_time
FROM TestTable t
) t