幂 M Query/Kusto 从组中取第一

Power M Query/Kusto take first from group

我有一个 table 看起来像这样:

id  timestamp  value1  value2
 1  09:12:37     1       1
 1  09:12:42     1       2
 1  09:12:41     1       3
 1  10:52:16     2       4
 1  10:52:18     2       5
 2  09:33:12     3       1
 2  09:33:15     3       2
 2  09:33:13     3       3

我需要按 id 和 value1 分组。对于每个组,我希望拥有时间戳最高的行。

上面 table 的结果如下所示:

id  timestamp  value1  value2
 1  09:12:42     1       2
 2  09:33:15     3       2

我知道有一个汇总运算符会给我这个:

mytable
| project id, timestamp, value1, value2
| summarize max(timestamp) by id, value1

Result:
     id  timestamp  value1
      1  09:12:42     1
      2  09:33:15     3

但我也无法获得此行的 value2。

提前致谢

我找到了解决问题的方法,但可能还有更好的方法。

mytable
| project id, timestamp, value1, value2
| order by timestamp desc
| summarize max(timestamp), makelist(value2) by id, value1

结果:

 id  timestamp  value1  list_value2
  1  09:12:42     1     ["2", "3", "1"]
  2  09:33:15     3     ["2", "3", "1"]

现在您可以通过添加

来扩展查询
| project max_timestamp, id, value1, list_value2[0]

从该列表中获取第一个元素。用 0 和 length(list_value2)-1 之间的任何数字替换“0”以访问其他值。

还有一个建议: 我使用的时间戳是由 ApplicationInsights 生成的。在我们的代码中,我们调用 TrackTrace 来记录一些数据。如果您按此时间戳对行进行排序,则不能保证生成的行列表与代码中生成数据的顺序相同。

如果我正确理解你的问题,你应该可以使用 summarize arg_max():

文档:https://docs.microsoft.com/en-us/azure/kusto/query/arg-max-aggfunction

datatable(id:long, timestamp:datetime, value1:long, value2:long)
[
 1, datetime(2019-03-20 09:12:37), 1, 1,
 1, datetime(2019-03-20 09:12:42), 1, 2,
 1, datetime(2019-03-20 09:12:41), 1, 3,
 1, datetime(2019-03-20 10:52:16), 2, 4,
 1, datetime(2019-03-20 10:52:18), 2, 5, // this has the latest timestamp for id == 1
 2, datetime(2019-03-20 09:33:12), 3, 1,
 2, datetime(2019-03-20 09:33:15), 3, 2, // this has the latest timestamp for id == 2
 2, datetime(2019-03-20 09:33:13), 3, 3,
]
| summarize arg_max(timestamp, *) by id

这将导致:

| id | timestamp                   | value1 | value2 |
|----|-----------------------------|--------|--------|
| 2  | 2019-03-20 09:33:15.0000000 | 3      | 2      |
| 1  | 2019-03-20 10:52:18.0000000 | 2      | 5      |