I have a query in google sheets:
=query('GA4 - Product Data'!A:N,"SELECT D, SUM(H) GROUP BY D PIVOT N",1)
What I would like to do is sort this data by the final column from the pivot, which I usually do by wrapping in another query:
=query(query('GA4 - Product Data'!A:N,"SELECT D, SUM(H) GROUP BY D PIVOT N",1),"SELECT * ORDER BY Col13 DESC",1)
The problem is that the data I'm querying extends each day, and soon it will have an extra months worth of data, so the pivot will be 14 columns long rather than 13 and my sort won't work.
Is there a way in query so "always sort the final column" somehow? so its more dynamic than what I have?
thanks for any help.
tried googling but not sure where to go next
There is more than one way, but similar to what you have, you can use LET to name the first QUERY, and then use it to apply it and find the amount of columns:
=LET(q,query('GA4 - Product Data'!A:N,"SELECT D, SUM(H) GROUP BY D PIVOT N",1),
query(q,"SELECT * ORDER BY Col"&COLUMNS(q)&" DESC",1))