You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ClickHouse查询中如何按周分组?formatDateTime按周分组失效

ClickHouse按周分组实现方案

在ClickHouse中,直接用formatDateTime按周分组容易因为周数未结合年份、起始日定义不明确等问题失效,推荐以下两种可靠实现方式:

方式1:按每周起始日期分组(直观展示)

使用toStartOfWeek函数获取每周的起始时间(默认周一为一周首日,可通过第二个参数指定周日,如toStartOfWeek(added_on, 1)),再格式化后分组,能确保同一周的记录归为一组:

select formatDateTime(toStartOfWeek(added_on), '%d-%m-%y') as "week_start", 
count(id) as "Count of transactions"
from transaction 
where created_at >= '2022-12-01 00:00:00'
group by week_start 
order by week_start

方式2:按「年份-周数」格式分组

如果需要以「年-周」的形式展示分组维度,可结合%Y(年份)和%W(周数,周一为首日)或%U(周数,周日为首日)格式符,避免跨年周数重复导致的分组错误:

select formatDateTime(added_on, '%Y-%W') as "year_week", 
count(id) as "Count of transactions"
from transaction 
where created_at >= '2022-12-01 00:00:00'
group by year_week 
order by year_week

注意事项

  • 单独使用%W或%U分组时必须搭配年份,否则不同年份的相同周数会被合并,导致统计结果错误;
  • toStartOfWeek函数的第二个参数可指定周起始日:0代表周一,1代表周日,根据业务需求调整。

内容的提问来源于stack exchange,提问作者ust

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:50:32