Thanks,
this is a great way to achieve it, I just spent literally hours searching for a solution. Learning influx db still.
As grafana has evolved there is howto accomplish it with the current version.
- The query:

The important part here is field(state) followed by last. Then the group by that has a fill(previous). The syntax is different;
SELECT last("state") FROM "state" WHERE ("entity_id" = 'heating_mode') AND $timeFilter GROUP BY time(1m) fill(previous)
- We will need to add transforms to get the data.
We have 2 essential transformations here. First we remove the time without states, this is in my case happens because the database is new. You might not need it or even wish to count these “empty” states. Then the important transformation is the group by states and the will count the number of rows of each states.
- In the field settings set the unit to minutes(m).
You can of course groupby seconds in which case the unit will need to be seconds.
