pivot 插件

通过将输入表中某一列的唯一值转换为输出表的多个列来旋转表,并在必要时对最终输出中出现的任何其余列值执行聚合。

注意

如果未指定 OutputSchema,则插件 pivot 的输出架构基于输入数据。 因此,使用不同的数据输入多次执行插件可能产生不同的输出架构。 这也意味着,引用未包装列的查询随时可能“中断”。 因此,不建议将此插件用于自动化作业而不指定 OutputSchema 函数。

语法

T | evaluate pivot(pivotColumn[, aggregationFunction] [,column1[,column2 ... ]]) [:OutputSchema]

详细了解语法约定

参数

客户 类型​​ 必需 描述
pivotColumn string 要旋转的列。 此列中的每个唯一值将是输出表中的一个列。
aggregationFunction string 聚合函数用于将输入表中的多个行聚合到输出表中的单个行。 目前支持的函数:min()max()take_any()sum()dcount()avg()stdev()variance()make_list()make_bag()make_set()count()。 默认为 count()
column1, column2, ... string 一个列名,或逗号分隔的列名列表。 输出表将为每个指定列包含一个额外的列。 默认值是除已透视列和聚合列以外的所有列。
OutputSchema pivot 插件输出的所需列的名称和类型。

语法:(ColumnName:ColumnType [, ...] )

指定所需架构可以优化查询执行,因为无需首先运行实际查询即可浏览架构。 如果运行时架构与 OutputSchema 架构不匹配,则会引发错误。

返回

Pivot 返回包含指定列(column1column2……)及透视列的所有唯一值的旋转表。 已透视列的每个单元格都将包含聚合函数计算。

示例

按列透视

对于以“AL”开头的每个 EventType 和 State,计算此州内该类型的事件数。

StormEvents
| project State, EventType
| where State startswith "AL"
| where EventType has "Wind"
| evaluate pivot(State)

输出

EventType ALABAMA ALASKA
雷雨大风 352 1
High Wind 0 95
Extreme Cold/Wind Chill 0 10
Strong Wind 22 0

使用聚合函数按列进行透视

对于每个以“AR”开头的 EventType 和 State,显示直接死亡人数的总数。

StormEvents
| where State startswith "AR"
| project State, EventType, DeathsDirect
| where DeathsDirect > 0
| evaluate pivot(State, sum(DeathsDirect))

输出

EventType ARKANSAS ARIZONA
暴雨 1 0
雷雨大风 1 0
Lightning 0 1
山洪 0 6
Strong Wind 1 0
3 0

按包含聚合函数的列和单个附加列进行透视

结果与上一示例相同。

StormEvents
| where State startswith "AR"
| project State, EventType, DeathsDirect
| where DeathsDirect > 0
| evaluate pivot(State, sum(DeathsDirect), EventType)

输出

EventType ARKANSAS ARIZONA
暴雨 1 0
雷雨大风 1 0
Lightning 0 1
山洪 0 6
Strong Wind 1 0
3 0

指定已透视列、聚合函数和多个附加列

对于每个事件类型、源和州,计算直接死亡人数之和。

StormEvents
| where State startswith "AR"
| where DeathsDirect > 0
| evaluate pivot(State, sum(DeathsDirect), EventType, Source)

输出

EventType Source ARKANSAS ARIZONA
暴雨 灾害管理 1 0
雷雨大风 灾害管理 1 0
Lightning 报纸 0 1
山洪 专业观测员 0 2
山洪 Broadcast Media 0 3
山洪 报纸 0 1
Strong Wind 执法机构 1 0
报纸 3 0

针对查询定义的输出架构进行透视

以下示例在 StormEvents 表中选择特定列。 该示例使用显式架构定义,以便在运行实际查询之前可以评估各种优化。

StormEvents
| project State, EventType
| where EventType has "Wind"
| evaluate pivot(State): (EventType:string, ALABAMA:long, ALASKA:long)

输出

EventType ALABAMA ALASKA
雷雨大风 352 1
High Wind 0 95
Marine Thunderstorm Wind 0 0
Strong Wind 22 0
Extreme Cold/Wind Chill 0 10
冷/寒风 0 0
海洋超强风 0 0
海洋强风 0 0