Adding numbers in a dynamic string separated by some token in the kusto table

Suppose there is a table like below:

datatable(str:string) [
    "a,b,2,10,d,e;a,b,c,14,d,e;a,b,c,10,d,e",
    "a,b,c,11,d,e;a,b,c,12,d,e;a,b,c,13,d,e;a,b,c,10,d,e",
    "a,b,c,20,d,e;a,b,c,25,d,e",
]

I need to add 4th value in each string separated by semicolon
e.g. Answer for above table is

10+14+10=34
11+12+13+10=46
20+25=45

I tried below which works for single row:

let calculateCostForARow = (str:string) {
    print row = split(str,";")
    | mv-expand row
    | parse row with * "," * "," * "," cost:long "," * 
    | summarize sum(cost)
};
calculateCostForARow("a,b,c,11,d,e;a,b,c,12,d,e;a,b,c,13,d,e;a,b,c,10,d,e")

but doesn’t work for table as to_scalar has issues with table

let calculateCostForARow = (str:string) {
    toscalar(print row = split(str,";")
    | mv-expand row
    | parse row with * "," * "," * "," cost:long "," * 
    | summarize sum(cost))
};
datatable(str:string) [
    "a,b,c,10,d,e;a,b,c,10,d,e;a,b,c,10,d,e",
    "a,b,c,10,d,e;a,b,c,10,d,e;a,b,c,10,d,e;a,b,c,10,d,e",
    "a,b,c,10,d,e;a,b,c,10,d,e",
]
| project calculateCostForARow(str)

Let me know if there are other ways to do this?

>Solution :

you could try this, using mv-apply:

datatable(str:string) [
    "a,b,2,10,d,e;a,b,c,14,d,e;a,b,c,10,d,e",
    "a,b,c,11,d,e;a,b,c,12,d,e;a,b,c,13,d,e;a,b,c,10,d,e",
    "a,b,c,20,d,e;a,b,c,25,d,e",
]
| mv-apply s = split(str, ";") on (
    summarize result = sum(tolong(split(s, ",", 3)[0]))
)
str result
a,b,2,10,d,e;a,b,c,14,d,e;a,b,c,10,d,e 34
a,b,c,11,d,e;a,b,c,12,d,e;a,b,c,13,d,e;a,b,c,10,d,e 46
a,b,c,20,d,e;a,b,c,25,d,e 45

Leave a Reply