Computing an Average Across Pivot Columns

Looker will not be updating this content, nor guarantees that everything is up-to-date. 


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.

d1454b8c-6206-4d3f-b874-3e4a04788e35.png

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}))
508f8075-6269-468d-a954-672fdb6364ee.png

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.

Version history
Last update:
‎06-23-2022 09:36 AM
Updated by: