bin()

将值向下舍入到给定 bin 大小的整数倍。

经常与 summarize by ... 结合使用。 如果有一组离散值,它们会分组成较小的特定值集。

bin()floor() 函数是等效的

语法

bin(value,roundTo)

详细了解语法约定

参数

客户 类型​​ 必需 Description
value int、long、real、timespan 或 datetime 要向下舍入的值。
roundTo int、long、real 或 timespan 除以 value 的“箱大小”。

返回

最接近以下 valueroundTo 倍数。 Null 值、null bin 大小或负的 bin 大小将导致 null。

示例

数值箱

print bin(4.5, 1)

输出

print_0
4

时间范围箱

print bin(time(16d), 7d)

输出

print_0
14:00:00:00

日期/时间箱

print bin(datetime(1970-05-11 13:45:07), 1d)

输出

print_0
1970-05-11T00:00:00Z

用 null 箱填充表

当箱行的表中没有对应行时,建议用这些箱来填充表。以下查询查看加利福尼亚州 4 月的某一周的强风暴事件。 但是,某些日子里没有事件。

let Start = datetime('2007-04-07');
let End = Start + 7d;
StormEvents
| where StartTime between (Start .. End)
| where State == "CALIFORNIA" and EventType == "Strong Wind"
| summarize PropertyDamage=sum(DamageProperty) by bin(StartTime, 1d)

输出

StartTime PropertyDamage
2007-04-08T00:00:00Z 3000
2007-04-11T00:00:00Z 1000
2007-04-12T00:00:00Z 105000

为了表示整周,以下查询对缺失天数使用 null 值填充结果表。 下面是此过程的分步说明:

  1. 使用 union 运算符向表添加更多行。
  2. range 运算符将生成只有一行一列的表。
  3. 基于 range 函数的 mv-expand 运算符会根据 StartTimeEndTime 之间的箱数创建相同数目的行。
  4. 使用一个值为 0PropertyDamage
  5. summarize 运算符将原始表中的箱分组到 union 表达式生成的表中。 此过程可确保输出中每个箱都有一行,其值为零或为原始计数。
let Start = datetime('2007-04-07');
let End = Start + 7d;
StormEvents
| where StartTime between (Start .. End)
| where State == "CALIFORNIA" and EventType == "Strong Wind"
| union (
    range x from 1 to 1 step 1
    | mv-expand StartTime=range(Start, End, 1d) to typeof(datetime)
    | extend PropertyDamage=0
    )
| summarize PropertyDamage=sum(DamageProperty) by bin(StartTime, 1d)

输出

StartTime PropertyDamage
2007-04-07T00:00:00Z 0
2007-04-08T00:00:00Z 3000
2007-04-09T00:00:00Z 0
2007-04-10T00:00:00Z 0
2007-04-11T00:00:00Z 1000
2007-04-12T00:00:00Z 105000
2007-04-13T00:00:00Z 0
2007-04-14T00:00:00Z 0