Templating fields when using subqueries

Hi. I’ve read https://github.com/grafana/grafana/issues/6248 and got to create variables by the use of templates and replace fields in simple queries, such as this one:

SELECT sum(/^$dirThput$/) FROM “stats_Ports” WHERE (“ip_system” =~ /^$ip_system$/ AND “port_name” =~ /^$port_name$/) AND $timeFilter GROUP BY time(15m), “port_name”

So far, so good …

Now, the problem arises with when using subqueries. For example, let’s say I have both an innerQuery and an outerQuery, such as:

innerQ = SELECT MAX(/^$dirRate$/) FROM “stats_Ports” WHERE “ip_system” =~ /^$ip_system$/ AND “port_name” =~ /^$port_name$/ AND $timeFilter GROUP BY time(60m), “port_name”

outerQ = SELECT MEAN(/^$dirRate$/) FROM ( innerQ ) WHERE $timeFilter GROUP BY time(60m), “port_name”

If I use variables, I get no points. But, if use the static fields from the measurement itself (I mean: no templating), then the outerQ does return points.

How to use templates in this scenario?

Thanks!

Not sure, anything wrong with the query grafana sends to influxdb? Do you see an issue there?

Well, not sure if there is something wrong with it. Nevertheless, I found a workaround to my problem.

I rewrote my outer query so as to bring everything (*) instead of a given field.

  • Previous:
    innerQ = SELECT MAX(/^$dirRate$/) FROM “stats_Ports” WHERE “ip_system” =~ /^$ip_system$/ AND “port_name” =~ /^$port_name$/ AND $timeFilter GROUP BY time(60m), “port_name”
    outerQ = SELECT MEAN(/^$dirRate$/) FROM ( innerQ ) WHERE $timeFilter GROUP BY time(60m), “port_name”

  • Now:
    innerQ = SELECT MAX(/^$dirRate$/) FROM “stats_Ports” WHERE “ip_system” =~ /^$ip_system$/ AND “port_name” =~ /^$port_name$/ AND $timeFilter GROUP BY time(60m), “port_name”
    outerQ = SELECT MEAN(*) FROM ( innerQ ) WHERE $timeFilter GROUP BY time(60m), “port_name”

Still don’t know if this is an issue on influx or grafana, but it’s now working.

Lucas!

Almost a year late here, but likely the way to do this is (outside of your workaround) is to include an alias for your MAX(/^dirRate/).
The current query would return a list of values with a field key of “MAX”.

So MAX(/^dirRate/) AS /^dirRate/ (or something like it) would allow passing the field key to the outer query, which would then be picked up correctly.