计算按国家和日期分组的百分比差异

Calculate difference in percent grouped on Country and Date

我已经可以计算按日期分组的百分比差异,

let t = (datatable(Value:int, Date:datetime, Сountry:string) 
[1000, '2018-01-01', "USA",    // 1 Jan == 100% 
 2000, '2018-01-01', "Poland", // this 100% also because grouped by Date 
 3000, '2018-01-02', "USA",    // 2 Jan == 233% because compared with 1 Jan
 4000, '2018-01-02', "Poland", // 233% also
]);

let val_2018 = toscalar(t | where Date >= datetime(2018-01-01) and Date < datetime(2018-01-02) | summarize sum(Value) ); 吨 |按 Date

汇总百分比 = 100.0 * sum(Value) / val_2018

所以我需要得到 4 条这样的记录:

1 Jan, USA, 100%
1 Jan, Poland, 100%
2 Jan, USA, 300%
2 Jan, Poland, 200%

但是如何添加按国家/地区分组?据我所知,需要在所有“总结”中添加“by Сountry”,但 toscalar 不能在“summarize”之后添加“by”:(

您可以组合使用 prev() and iff() 函数。

例如:

datatable(['value']: int, ['date']: datetime, ['country']: string) [
    1000, datetime(2018-01-01), "USA",   
    2000, datetime(2018-01-01), "Poland",
    3000, datetime(2018-01-02), "USA",   
    4000, datetime(2018-01-02), "Poland",
]
| order by country asc, ['date'] asc
| extend percentage = iff(
    prev(country) == country,
    100.0 * value / prev(value),
    100.0)
value date country percentage
2000 2018-01-01 00:00:00.0000000 Poland 100
4000 2018-01-02 00:00:00.0000000 Poland 200
1000 2018-01-01 00:00:00.0000000 USA 100
3000 2018-01-02 00:00:00.0000000 USA 300