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

如何用KQL将列中唯一值设为列名并实现通用统计查询

KQL通用类别列转换:自动按类别生成计数列

你当前的手动实现需要逐个指定类别名称,新增类别时必须修改查询代码。可以用KQL的pivot运算符实现完全通用的查询,自动把category列的唯一条目转为列名并展示对应计数,新增类别无需改动代码。

通用实现代码

let sales = datatable (store: string, category: string, product: string)
[
    "StoreA", "Food", "Steak",
    "StoreB", "Drink", "Cola",
    "StoreB", "Food", "Fries",
    "StoreA", "Sweets", "Cake",
    "StoreB", "Food", "Hotdog",
    "StoreB", "Food", "Salad",
    "StoreA", "Sweets", "Chocolate",
    "StoreC", "Food", "Steak"
];
sales
| summarize count() by store, category
| pivot category, sum(count_)

代码逻辑说明

  1. 分组统计基础计数:summarize count() by store, category先按门店和类别做分组统计,得到每个门店下每个类别的商品数量。
  2. 自动行转列:pivot category, sum(count_)会自动识别category列的所有唯一项,将其转为列名,并通过sum聚合每个列对应的计数(这里因为已经按门店+类别分组过,sum实际就是直接取分组后的计数值)。

可选优化:补全空值为0

如果希望没有对应类别的门店显示0而非空值,可以在pivot后添加fillna(0):

let sales = datatable (store: string, category: string, product: string)
[
    "StoreA", "Food", "Steak",
    "StoreB", "Drink", "Cola",
    "StoreB", "Food", "Fries",
    "StoreA", "Sweets", "Cake",
    "StoreB", "Food", "Hotdog",
    "StoreB", "Food", "Salad",
    "StoreA", "Sweets", "Chocolate",
    "StoreC", "Food", "Steak"
];
sales
| summarize count() by store, category
| pivot category, sum(count_)
| fillna(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:20:29