【问题标题】:Writing SQL Query for a Specific Time Range为特定时间范围编写 SQL 查询
【发布时间】:2021-09-17 12:11:43
【问题描述】:

我需要在 [05/Sep/2017] 的 11:36 到 11:37 的整整两分钟时间段内编写一个查询访问站点的次数。根据数据集,我知道答案应该是 7,但是我输入的所有内容都给我一个零输出。我已经尝试过这些值之间的时间戳。我已经尝试过 min=x 和 max=y 的时间戳。我不确定我的格式是不正确还是什么,但我从 2:30 开始一直在苦苦挣扎,我越来越绝望了。 This is what my query looks like. I have tried a few different operations but this is the most recent attempt

【问题讨论】:

  • (1) 用您正在使用的数据库标记您的问题。 (2) 提供样本数据和期望的结果。 (3) 你使用的列的数据类型是什么?
  • 我正在使用时间戳列。我的数据库是 SQLite。我尝试了您在下面显示的查询设置,但它仍然给我输出 0。
  • 表格中日期的格式是什么?
  • 表格中的日期格式为 [05/Sep/2017 后跟时间,因此完整的时间戳列的值类似于 [05/Sep/2017:11:29:31]

标签: sql sqlite timestamp


【解决方案1】:

您可以使用 datepart 来构建上下限时间范围。我展示了如何在 bigint 中保留所有比较

declare @StartDate as datetime='2020-10-19 11:36:00'
declare @EndDate as datetime='2020-10-19 11:37:00'

SELECT [created_at]
 ,cast(replace(replace(replace(convert(varchar(19),[created_at], 
 121),':',''),'-',''),' ','') as bigint) int_date,

 cast(DATEPART(year, @StartDate) * 10000 + DATEPART(month, @StartDate) * 100 + 
DATEPART(day, @StartDate) as varchar)+format(datepart(Hour,@StartDate),'0#')+format(datepart(Minute,@StartDate),'0#')
+format(datepart(Second,@StartDate),'0#')
int_date_compare

FROM mytable
 where cast(replace(replace(replace(convert(varchar(19),[created_at], 121),':',''),'-',''),' ','') as bigint) 
  >=
 cast(DATEPART(year, @StartDate) * 10000 + DATEPART(month, @StartDate) * 100 + 
DATEPART(day, @StartDate) as varchar)+format(datepart(Hour,@StartDate),'0#')+format(datepart(Minute,@StartDate),'0#')
 +format(datepart(Second,@StartDate),'0#')
 <=
 cast(DATEPART(year, @EndDate) * 10000 + DATEPART(month, @EndDate) * 100 + 
 DATEPART(day, @StartDate) as varchar)+format(datepart(Hour,@EndDate),'0#')+format(datepart(Minute,@EndDate),'0#')
+format(datepart(Second,@EndDate),'0#')
order by created_at

【讨论】:

    【解决方案2】:

    我希望查询如下所示:

    select count(*)
    from t
    where col >= '2017-09-05 11:36:00' and
          col < '2017-09-05 11:38:00'
    

    日期/时间常数的确切格式因数据库而异,但这是一种典型格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 2017-07-01
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多