Is it possible to control the ordering of the array values created by array_agg()?

akisugi
New Contributor III

Hi! I would be glad to ask you some questions.

I have the following data. 

スクリーンショット 2024-04-06 23.08.15.png

I would like to get this kind of result. I want `move` to correspond to the order of `hist`.

スクリーンショット 2024-04-06 23.07.34.png

Therefore, i considered the following query.

```

with tmp as (
select * from (values
(1, 1, 'a'),
(1, 3, 'c'),
(1, 2, 'b'),
(2, 1, 'a'),
(2, 2, 'b'),
(2, 3, null),
(3, 3, 'b'),
(3, 1, 'a'),
(3, 2, null),
(4, 1, 'a')
) as tab(custid, hist, alf)
order by custid asc, hist asc
)
select
custid,
array_join(array_agg(alf), ' -> ') as move
from tmp
group by custid
order by custid asc;
```

Tried sorting by `order by` before combining strings into an array with `array_join(array_agg())`. At first glance it seems to work, but the official documentation for `array_agg()` states the following

```
The order of elements in the array is non-deterministic.

From | https://docs.databricks.com/en/sql/language-manual/functions/array_agg.html#:~:text=The%20order%20of....
```

Does it make sense to sort by `order by` before running `array_join(array_agg())`? Will it work as expected with larger data sizes?

I apologize for the inconvenience and would appreciate your response.