clickhouseSQL日期相关

1. 毫秒级时间戳转日期/小时

sql 复制代码
--13位时间戳转具体时间
toDateTime(report_time / 1000) as _c00 

-- 获取时间戳对应的时间点整点(结果:%Y-%m-%d %H:00:00.0) eg:2022-09-28 23:00:00.0
toStartOfHour(toDateTime(report_time / 1000)) AS _10

-- 获取时间点整点(结果无日期:%H)eg:23
toHour(FROM_UNIXTIME(report_time div 1000)) as _100

-- 13位时间戳转成年月日时(结果:%Y-%m-%d %H)
FROM_UNIXTIME(report_time div 1000,'%Y-%m-%d %H') 


-- 获取时间戳对应的日期开始时间(结果:%Y-%m-%d 00:00:00.0)eg:2022-09-28 00:00:00.0
toStartOfDay(toDateTime(report_time / 1000)) AS _02

--获取时间戳对应的日期(结果:%Y-%m-%d)eg:2022-09-28
toDate(toDateTime(report_time / 1000)) AS _01
toDate(toStartOfDay(toDateTime(report_time / 1000))) AS _0

-- 获取n分钟间隔(eg,10分钟间隔指00-09,10-19......55-59)
toStartOfInterval(toDateTime(report_time / 1000), INTERVAL 10  minute)

-- 字符串时间转datetime
toDateTime('2023-02-02 01:02:15')

结果如下:

● "/"和"div"的区别

"/"非整除,结果仍然是浮点数

"div"为整除,得到10位数结果

2. 当前时间往前推

解决凌晨0点之后,例行时间是跑前一日23点数据的问题

sql 复制代码
-- 获取当前时间
now()

-- 当前时间前推1小时
date_sub(hour, 1, now())

-- 再转换为日期
toDate(date_sub(hour, 1, now()))

-- 前推n天
date_sub(day,7,toDate(date_sub(hour,1,now())))--前推7天

-- 当前时间往前推1小时,并转化为int8格式
toInt8(substring(cast(date_sub(hour, 1, toDateTime('2023-02-02 01:02:15')) as String), 12, 2))
toInt8(substring(CAST(minus(toDateTime('2023-02-02 01:02:15'), toIntervalHour(1)), 'String'), 12, 2))
-- toDateTime('2023-02-02 01:02:15') = now()
相关推荐
shushangyun_43 分钟前
2026智能采购商城系统选型指南:如何引领企业数字化采购升级
java·大数据·数据库·人工智能·机器学习
dexi.Chi 攻城狮1 小时前
SQL层次查询语法
经验分享·笔记·sql
华山令狐虫2 小时前
DBAPI AI 写 SQL:支持动态 SQL 与参数占位符,自然语言一键生成
数据库·人工智能·sql·dbapi
IvorySQL2 小时前
PG 技术日报|2026-07-04
数据库·人工智能·postgresql·开源
Hoxy.R2 小时前
KingbaseES读写分离高可用集群扩容、备库重建与故障切换实战
运维·数据库
IvorySQL3 小时前
IvorySQL HTAP 实时湖仓接入引擎
数据库·postgresql·开源·htap·ivorysql
忧郁的紫菜3 小时前
WCF+JSON+实体对象与WebService+DataSet效率大比拼
数据库·oracle·json
IvorySQL3 小时前
PostgreSQL 技术日报|2026-07-05
数据库·postgresql
我会尽全力 乐观而坚强4 小时前
MySQL库与表的操作
linux·数据库·mysql
lilihuigz4 小时前
产品附加选项插件WooCommerce Product Add-Ons:9种字段类型与3种定价模式提升销售 - 易服客工作室
数据库·mysql·wordpress插件·woocommerce扩展·定制选项