Requirement: order by clause within array_agg() function in Snowflake
create table test("CompanyID","GroupIDs","GroupNames")as select*from(values(1111 ,1 ,'ABC'), (1111 ,5 ,'PRS')); Expected output
| CompanyID | GroupIDs | GroupNames |
|---|---|---|
| 1111 | [1, 5] | [ABC, PRS] |
Here in above example, it's in ascending order and GroupID=1 corresponds to GroupName=ABC and so on.
Below sql doesn't order by groupid in the final result
SELECT companyid, ARRAY_AGG(groupid) AS groupid, ARRAY_AGG(groupname) AS groupname FROM ( SELECT cgd.companyid ,cg.groupid,cgd.companyname,cg.groupname FROM gd LEFT JOIN cg ON cg.groupid = cgd.groupid ORDER BY cgd.companyid , cg.groupid, cg.groupname ) t GROUP BY ALL; Above query produces results as below
| CompanyID | GroupIDs | GroupNames |
|---|---|---|
| 1111 | [5,1] | [PRS, ABC] |