Math Expressions on each Instance from Two Queries

I am using Prometheus database to store data of switches. Each switch has a “ramFree” and a “ramUsed” column that contains an amount of bytes. What I want to do is perform a simple math operation to get the percentage of used ram for each switch by doing the following equation:

(ramUsed / (ramFree + ramUsed)) * 100

I am able to do this using the “Math Expression” feature after the query, but it only works when querying for one specific switch. What I want is to have it perform the math operation for each switch (or instance) returned in the query and display the percentage result for each switch (instance) on the graph panel. If I have it do the expression when the query returns more than one switch, it shows a “No data” error.

I was able to figure it out by performing the math operations within the query itself and grouping it by instance. Just replying to help others who may have the same issue.

I used the following PromQL query below:
(sum(ramUsed) by (instance) / (sum(ramFree) by (instance) + sum(ramUsed) by (instance))) * 100