The solution is to use a single query with GROUP BY and a Grafana transformation that transposes the table:
SELECT roomid AS "room id", SUM(mvalue) AS "energy consumption in the room" FROM periodic_measurements WHERE ($__timeFilter(mtimestamp) AND apartmentid = $apartment AND metric = 5) GROUP BY roomid;