BEGIN; BEGIN select c_count, count(*) as custdist from ( select c_custkey, count(o_orderkey) from customer left outer join orders on c_custkey = o_custkey and o_comment not like '%unusual%packages%' group by c_custkey ) as c_orders (c_custkey, c_count) group by c_count order by custdist desc, c_count desc; c_count | custdist ---------+---------- 0 | 500021 10 | 66163 9 | 65117 11 | 62215 8 | 58325 12 | 55802 13 | 49671 19 | 46828 7 | 46391 18 | 46136 14 | 45551 20 | 45207 17 | 45009 15 | 43762 16 | 43758 21 | 42216 22 | 38173 6 | 32677 23 | 32530 24 | 26944 25 | 21237 5 | 19698 26 | 15976 27 | 11846 4 | 9947 28 | 8085 29 | 5691 3 | 3984 30 | 3779 31 | 2405 32 | 1507 2 | 1173 33 | 864 34 | 485 35 | 290 1 | 232 36 | 131 37 | 82 38 | 41 39 | 27 40 | 11 41 | 6 42 | 3 45 | 2 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT