SQL查询可在时间戳列中无小时获取数据

问题描述

我编写了代码SQL查询以从数据库获取数据:

sql_tables <- glue("
SELECT *
FROM mytable
LIMIT 4
")
table <- dbGetQuery(con,stri_encode(sql_tables,to = "UTF-8")) %>%
     as.data.frame()

我得到了这个数据框:

ID      value                    timestamp
1       message sent      2019-05-29 06:45:34
2       sold out          2019-05-29 07:55:29
3       processed         2019-05-30 17:42:11
4       processed         2019-05-30 19:44:15

我想编写另一个查询以仅获取2019-05-29的数据:

sql_tables <- glue("
SELECT *
FROM mytable
WHERE timestamp = '2019-05-29'
LIMIT 4
")
table <- dbGetQuery(con,to = "UTF-8")) %>%
     as.data.frame()

但这给我带来了一个错误

Error in select(conn@ptr,statement) :
  DB::Exception: Key expression contains comparison between inconvertible types: DateTime and String inside timestamp = '2019-05-29'

我该怎么做?如何在SQL查询的“时间戳”列中省去数小时?所需的结果是:

ID      value                    timestamp
1       message sent      2019-05-29
2       sold out          2019-05-29 

解决方法

来自manuals data types for date

日期。自1970年1月1日以来以两字节存储为天数 (未签名)。允许存储刚开始的值 Unix Epoch到由常量定义的上限 编制阶段(目前是2106年,但是 最终获得完全支持的年份是2105。

存储的日期值不带时区。

因此我们需要将"2019-05-29"日期转换为数字:

as.numeric(as.Date("2019-05-29"))
# [1] 18045

#Origin is same as clickhouse,test:
as.Date(18045,origin = "1970-01-01")
# [1] "2019-05-29"

现在我们可以将其用作数字(未经测试):

SELECT *
FROM mytable
WHERE timestamp = 18045
LIMIT 4
,
  1. toDate(timestamp)

    选择* 来自mytable WHERE toDate(时间戳)='2019-05-29' LIMIT 4

  2. 选择* 来自mytable 时间戳=> toDateTime('2019-05-29')和时间戳