SELECT region, country, category, max(multiIf(rownumber = 1, app, '')) AS col1, max(multiIf(rownumber = 2, app, '')) AS col2, max(multiIf(rownumber = 3, app, '')) AS col3, max(multiIf(rownumber = 4, app, '')) AS col4, max(multiIf(rownumber = 5, app, '')) AS col5, max(multiIf(rownumber = 6, app, '')) AS col6, max(multiIf(rownumber = 7, app, '')) AS col7, max(multiIf(rownumber = 8, app, '')) AS col8, max(multiIf(rownumber = 9, app, '')) AS col9, max(multiIf(rownumber = 10, app, '')) AS col10, max(multiIf(rownumber = 11, app, '')) AS col11, max(multiIf(rownumber = 12, app, '')) AS col12, max(multiIf(rownumber = 13, app, '')) AS col13, max(multiIf(rownumber = 14, app, '')) AS col14, max(multiIf(rownumber = 15, app, '')) AS col15, max(multiIf(rownumber = 16, app, '')) AS col16, max(multiIf(rownumber = 17, app, '')) AS col17, max(multiIf(rownumber = 18, app, '')) AS col18, max(multiIf(rownumber = 19, app, '')) AS col19, max(multiIf(rownumber = 20, app, '')) AS col20, max(multiIf(rownumber = 21, app, '')) AS col21, max(multiIf(rownumber = 22, app, '')) AS col22, max(multiIf(rownumber = 23, app, '')) AS col23, max(multiIf(rownumber = 24, app, '')) AS col24, max(multiIf(rownumber = 25, app, '')) AS col25, max(multiIf(rownumber = 26, app, '')) AS col26, max(multiIf(rownumber = 27, app, '')) AS col27, max(multiIf(rownumber = 28, app, '')) AS col28, max(multiIf(rownumber = 29, app, '')) AS col29, max(multiIf(rownumber = 30, app, '')) AS col30 FROM ( SELECT region, country, category, app, weight, rownumber FROM ( SELECT region, country, category, groupArray(app_id) AS arr_app, groupArray(weight) AS arr_weight, arrayEnumerate(arr_weight) AS rownumber FROM ( SELECT region, country, category, app_id, (sum(active_cnt) / sum(total_active_cnt)) * (sum(duration) / sum(vd_dt_cnt)) AS weight FROM test.f_local_app_rank GROUP BY region, country, category, app_id ORDER BY weight DESC ) AS A GROUP BY region, country, category ) AS AA ARRAY JOIN arr_app AS app, arr_weight AS weight, rownumber ) AS AAA GROUP BY region, country, category ORDER BY region ASC, country ASC, category ASC FORMAT CSV