Starting in Looker 21.12, you can use Quick Calculations to perform common calculations on numeric fields that are in an Explore's data table without using Looker functions and operators when the Custom Fields Labs feature is enabled, and you have permission to use them.
The Problem
When we have a result set like the one below, we might want to compute the average for each state across the pivot columns. In Looker table calculations, this is achieved with the mean()
function.
To compute our average, we need to find the sum of the values across each row, and then divide that sum by the number of columns. We can do this by creating a table calculation with the example below.
An Elegant Solution
We'll take advantage of the pivot_row()
function to help us dynamically sum the row values across pivot columns and get the right column number.
The pivot_row()
function takes the values from all columns across a row and returns them in a concatenated list. For more detail, see this Help Center article on using pivot_row()
in table calculations.
First, we'll use pivot_row()
to get a list of all the values across each row:
pivot_row(${order_items.count})
Then, we'll generate an average by taking the mean of this list:
mean(pivot_row(${order_items.count}))
You can also use the second table calculation on its own, as it combines and performs both the pivot_row()
and mean()
operations on the values in the table.
Now, we have an elegant average of the pivot row, as shown above.