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

Kusto查询语言:如何将Datetime取整至最近月份并按月统计日志

解决日志按月统计及多时间间隔支持的问题

问题原因

使用 bin(Date, 30d) 无法正确按月分组,因为不同月份的天数存在差异(28-31天),固定30天的时间桶会与自然月的边界错位,导致像2月的日志被错误归入1月的统计桶中。

解决方案

利用Kusto内置的 startofmonth() 函数获取每条日志所属月份的起始时间,以此作为分组依据,就能精准实现自然月的统计。同时通过条件判断兼容1h、1d、7d等其他时间间隔参数,无需手动提取年月信息。

示例查询

// 可替换为 '1h'、'1d'、'7d' 或 'month'
let TargetInterval = 'month'; 
datatable(Date:datetime, Log:string)[
datetime(2018-02-02T15:14),"log1",
datetime(2018-03-23T12:14),"log2",
datetime(2018-03-24T16:14),"log3",
datetime(2019-04-26T15:14),"log4"]
| summarize count_Log = count(Log) by 
    DateBin = case(
        TargetInterval == 'month', startofmonth(Date),
        bin(Date, totimespan(TargetInterval))
    )
// 格式化输出以匹配期望的日期格式
| project Date = format_datetime(DateBin, 'yyyy-MM 00:00:00.0000000'), count_Log

输出结果

当 TargetInterval = 'month' 时,运行上述查询会得到符合预期的结果:

Date                    count_Log
2018-02 00:00:00.0000000    1
2018-03 00:00:00.0000000    2
2019-04 00:00:00.0000000    1

关键说明

  • startofmonth(Date):直接返回日志时间所属月份的第一天0点,完美对齐自然月边界。
  • case() 语句:根据传入的时间间隔参数自动切换分组逻辑——如果是按月统计则用 startofmonth,否则用 bin() 处理小时、天、周等固定间隔。
  • format_datetime():将分组后的时间桶格式化为指定字符串样式,确保输出符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:52:40