【问题标题】:SQL query to get data without hours in timestamp columnSQL查询以获取时间戳列中没有小时的数据
【发布时间】:2020-11-03 09:11:48
【问题描述】:

我已经编写了一个代码和 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, stri_encode(sql_tables, 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 

【问题讨论】:

  • 您好,不确定您使用的是什么数据库?您可以转换时间戳或从时间戳中提取日期来进行比较
  • @DPH 它的点击室
  • 看看这个问题 - 可能你正在寻找的答案在这里:stackoverflow.com/questions/55788679/…

标签: sql r clickhouse


【解决方案1】:
  1. toDate(时间戳)

    选择 * 来自我的表 WHERE toDate(时间戳)='2019-05-29' 限制 4

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

【讨论】:

    【解决方案2】:

    来自manuals data types for date

    日期。存储在两个字节中,作为自 1970-01-01 以来的天数 (未签名)。允许存储刚开始之后的值 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
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 2020-06-14
      • 2019-09-12
      • 1970-01-01
      • 2015-12-09
      • 2022-10-13
      相关资源
      最近更新 更多