Google Sheets QUERY: Pivot Data

PIVOT

Thanks to PIVOT, it is possible to add new result columns from unique data in a column.


Example of Use

The following example displays the sum of messages (E) for each rank (D):

=QUERY(DB!A1:G15,"SELECT D, SUM(E) GROUP BY D")
google sheets function query format sum

To display the ranks as a column (with one column per different rank) and the corresponding sum underneath, enter:

=QUERY(DB!A1:G15,"SELECT SUM(E) PIVOT D")
google sheets function query pivot
In this case, PIVOT pivoted the ranks to display one rank per column instead of displaying one rank per row.

It is also possible to modify the headers:

=QUERY(DB!A1:G15,"SELECT SUM(E) PIVOT D LABEL SUM(E) '(rank)'")
google sheets function query pivot label

Advanced Use Case

The following example displays the sum of messages (E) for each rank (D):

=QUERY(DB!A1:G15,"SELECT D, SUM(E) GROUP BY D")
google sheets function query format sum

The goal this time is to display the sum of messages for each rank (D) and for each month (B).

To achieve this result, one or the other of these data will therefore have to be pivoted.

To pivot based on ranks (D), enter:

=QUERY(DB!A1:G15,"SELECT MONTH(B), SUM(E) GROUP BY MONTH(B) PIVOT D")
google sheets function query pivot sum date month

To pivot based on the months of dates (B), enter:

=QUERY(DB!A1:G15,"SELECT D, SUM(E) GROUP BY D PIVOT MONTH(B)")
google sheets function query pivot group by

The same query with the addition of LABEL and FORMAT:

=QUERY(DB!A1:G15,"SELECT D, SUM(E) GROUP BY D PIVOT MONTH(B) LABEL SUM(E) '/ 2023', D '' FORMAT D 'Rank 0'")

google sheets function query pivot group by label format png