Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigQuery GROUP_CONCAT and ORDER BY

I am currently using BigQuery and GROUP_CONCAT which works perfectly fine. However, when I try to add a ORDER BY clause to the GROUP_CONCAT statement like I would do in SQL, I receive an error.

So e.g., something like

SELECT a, GROUP_CONCAT(b ORDER BY c) FROM test GROUP BY a

The same happens if I try to specify the separator.

Any ideas on how to approach this?

like image 732
fsociety Avatar asked Jul 12 '15 13:07

fsociety


People also ask

How do you select top 10 rows in BigQuery?

Instead, use the handy preview feature in BigQuery. Just click on the table name, and then click on the Preview tab to see the top 100 rows.

What does Array_agg do in BigQuery?

ARRAY_AGG. Returns an ARRAY of expression values. To learn more about the optional arguments in this function and how to use them, see Aggregate function calls.

How do you Unnest an array in BigQuery?

To convert an ARRAY into a set of rows, also known as "flattening," use the UNNEST operator. UNNEST takes an ARRAY and returns a table with a single row for each element in the ARRAY . Because UNNEST destroys the order of the ARRAY elements, you may wish to restore order to the table.


1 Answers

Standard SQL mode in BigQuery does support ORDER BY clause within some aggregate functions, including STRING_AGG, for example:

#standardSQL
select string_agg(t.x order by t.y) 
from unnest([struct<x STRING, y INT64>('a', 5), ('b', 1), ('c', 10)]) t

will result in

b,a,c

Documentation is here: https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#using-order-by-with-aggregate-functions

like image 124
Mosha Pasumansky Avatar answered Nov 12 '22 03:11

Mosha Pasumansky