While writing a kusto query to create a custom chart on my azure dashboard, I want to be able to calculate the time grain based on the period the user selected on the dashboard.
For example: last 4h => time grain 2 mins, last 24h => 10 mins
I tried the following to calculate the period because we are still unable to access it (as far as I could find on the internet).
let timeGrain = traces
| summarize min_time = min(timestamp), max_time = max(timestamp)
| extend timeWindow = max_time - min_time // days / hrs/ min / seconds
| project timeWindow
| extend timeGrain = case(timeWindow <= 4h, "2m",
timeWindow <= 12h, "5m",
timeWindow <= 24h, "10m",
"2h")
| project timeGrain;
The query returns me the time grain I want to achieve but I am unable to use this variable inside of my other query.
traces
...
| summarize percentile(DurationInMs, 50) by bin(timestamp, timeGrain), CommandType
| render areachart with (ytitle = "Duration In Ms", xtitle = "Timestamp");
(I know traces isn't the best place to store data regarding duration, we are gonna change this to metrics but it's not the scope of the question)
This gives me the following error: 'summarize' operator: Failed to resolve scalar expression named 'timeGrain'
Is there a way to fix this error or is there a better way to create a dynamic time grain?