bin()

將值捨入為指定 bin 大小的整數倍數。

常用來與 summarize by ... 搭配使用。 如果您有一組散佈的值,這些值會分組成較小的特定值集。

bin()floor() 函式相等

語法

bin(value,roundTo)

深入瞭解 語法慣例

參數

名稱 類型 必要 Description
value int、long、real、 timespan 或 datetime ✔️ 要進位的值。
roundTo int、long、real 或 timespan ✔️ 分割 值的 「bin 大小」。

傳回

低於 value 的 roundTo 最接近倍數。 Null 值、Null 的間隔大小或負的間隔大小都會產生 Null。

範例

數值量化

print bin(4.5, 1)

輸出

print_0
4

Timespan bin

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 bin 填補數據表

當數據表中沒有對應數據列的 Bin 有數據列時,建議您將這些間隔填補數據表。下列查詢會在 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. mv-expand式上的 range 運算子會建立與 之間EndTime有間隔StartTime數目的數據列數目。
  4. 使用數量為 0PropertyDamage
  5. 運算子會將 summarize 原始數據表中的 bin 群組到表示式所產生的 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