【问题标题】:How to use timestamp column to get data between two dates?如何使用时间戳列获取两个日期之间的数据?
【发布时间】:2021-04-11 16:08:58
【问题描述】:

我有一个下面的查询,它提供了过去 X 天的数据。而不是我想在两个日期之间获取数据,如果可能的话应该可以配置?有什么办法吗?

SELECT processId,
 houroftheday,
 minuteofhour,
 listagg(clientId, ',') within group (order by minuteofhour) as clientIds,
 count(*) as psg
 FROM data.process
 where kite = 'BULLS'
 and code is null
 and timestampinepochsecond > date_part(epoch, sysdate) - X*24*60*60
 group by 1, 2, 3

timestampinepochsecond 列有这个值 - 1599608655

如何使用timestampinepochsecond 列获取两个日期之间的数据?如下所示:

 timestampinepochsecond between 2020-12-01 AND 2021-01-05

更新

我正在尝试声明两个变量并在我的查询中使用它们,如下所示,但它不起作用-

CREATE TEMP TABLE tmp_variables AS SELECT 
   cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint) AS StartDate, 
   cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-10 16:22:17.897' ) as bigint)      AS EndDate,
   5556::BIGINT       AS some_id;

SELECT StartDate, EndDate FROM tmp_variables;

【问题讨论】:

  • WHERE t.timestamp_col >= '2020-12-01' AND t.timestamp_col
  • 我的 timestampinepochsecond 列具有这样的值 - 1599608655 @MeghshyamSonar

标签: sql amazon-redshift


【解决方案1】:

我认为您必须将日期时间转换为 Epoch Timestamp,然后基于此进行查询:

    -- this will get the the timestamp in seconds
    DECLARE @startTimeStamp bigint = cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)

 DECLARE @endTimeStamp bigint = cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-10 16:22:17.897' ) as bigint)
    

-- then your query.

SELECT processId,
 houroftheday,
 minuteofhour,
 listagg(clientId, ',') within group (order by minuteofhour) as clientIds,
 count(*) as psg
 FROM data.process
 where kite = 'BULLS'
 and code is null
 and timestampinepochsecond >= @startTimeStamp  AND  timestampinepochsecond 
 < @endTimeStamp
 group by 1, 2, 3

如果这是一个存储过程 - 您可以传入开始日期,结束日期是一个参数 - 然后转换为纪元秒数。

【讨论】:

  • 对不起,我离开了一段时间。看起来我不能在这里使用Declare variables,然后在选择查询中使用。我也检查了here。有什么办法可以在红移中做到这一点?我想像您一样在顶部声明startTimeStampendTimeStamp,并在下面的选择查询中使用它们。这有可能做到吗?
  • 我在我的问题中更新了我尝试过的内容,但它给出了明显的语法错误 - 任何想法我在那里做错了什么?
猜你喜欢
  • 2014-05-22
  • 1970-01-01
  • 2019-05-07
  • 2017-10-03
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
相关资源
最近更新 更多