Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives of array_agg() or string_agg() on redshift

I am using this query to get the aggregated results:

select _bs, string_agg(_wbns, ',') from bag group by 1;

I am getting this error:

Error running query: function string_agg(character varying, "unknown") does not exist HINT: No function matches the given name and argument types. You may need to add explicit type casts.

I also tried array_agg() and getting the same error.

Please help me in figuring out the other options I can use to aggregate the results.

like image 362
Bhawan Avatar asked Sep 19 '18 12:09

Bhawan


People also ask

What does Listagg do in redshift?

For each group in a query, the LISTAGG window function orders the rows for that group according to the ORDER BY expression, then concatenates the values into a single string.

Which of the following feature is not supported in AWS redshift?

Amazon Redshift does not support locale-specific or user-defined collation sequences.

What is the use of String_agg?

STRING_AGG is an aggregate function that takes all expressions from rows and concatenates them into a single string. Expression values are implicitly converted to string types and then concatenated.

How do you create a series in redshift?

In Redshift, when we need a sequence of dates between two given days, we can create it using the generate_series function and use it as a table in a FROM or JOIN clause. It is useful when we need to display a table of dates and values, but we don't have a value for each of those days.


4 Answers

you have to use listagg for reshift

For each group in a query, the LISTAGG aggregate function orders the rows for that group according to the ORDER BY expression, then concatenates the values into a single string.

LISTAGG is a compute-node only function. The function returns an error if the query doesn't reference a user-defined table or Amazon Redshift system table.

Your query will be as like below

select _bs, 
listagg(_wbns,',')
within group (order by _wbns) as val
from bag
group by _bs
order by _bs;

for better understanding Listagg

like image 129
Zaynul Abadin Tuhin Avatar answered Sep 24 '22 12:09

Zaynul Abadin Tuhin


To get an array type back instead of a varchar, you need to combine the LISTAGG function with the SPLIT_TO_ARRAY function like so:

SELECT
  some_grouping_key,
  SPLIT_TO_ARRAY(LISTAGG(col_to_agg, ','), ',')
FROM some_table
GROUP BY 1
like image 40
Brideau Avatar answered Sep 22 '22 12:09

Brideau


Redshift has a listagg function you can use instead:

SELECT _bs, LISTAGG(_wbns, ',') FROM bag GROUP BY _bs;
like image 36
Mureinik Avatar answered Sep 25 '22 12:09

Mureinik


Use listagg function:

select _bs, 
listagg(_wbns,',')
within group (order by _bs) as val
from bag
group by _bs
like image 24
Fahmi Avatar answered Sep 25 '22 12:09

Fahmi