cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

create an array sorted by a field

data1233
New Contributor

How do i create an array from a field while applying sorting?

how do I do this in data brick since databricks does not support order by in array_agg?  same is possible in Snowflake and(Array agg) or Redshift(listagg). 

SELECT ARRAY_AGG(O_ORDERKEY) WITHIN GROUP (ORDER BY timestamp ASC)
  FROM orders 
+--------------------------------------------------------------+
| ARRAY_AGG(O_ORDERKEY) WITHIN GROUP (ORDER BYtimestamp ASC) |
|--------------------------------------------------------------|
| [                                                            |
|   41445,                                                     |
|   55937,                                                     |
|   67781,                                                     |
|   80550,                                                     |
|   95808,                                                     |
|   101700,                                                    |
|   103136                                                     |
| ]                                                            |
+--------------------------------------------------------------+

 

1 REPLY 1

feiyun0112
Honored Contributor
%sql
SELECT array_sort(array_agg(col)
  ,(left, right) -> CASE WHEN left < right THEN -1
    WHEN left > right THEN 1 ELSE 0 END) arr_col FROM VALUES (3), (2), (1) AS tab(col);

 

https://docs.databricks.com/en/sql/language-manual/functions/array_sort.html 

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group