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 | 66066 9 | 65181 11 | 62166 8 | 58279 12 | 56079 13 | 49546 19 | 46712 18 | 46351 7 | 46336 20 | 45311 14 | 45277 17 | 45006 15 | 43984 16 | 43729 21 | 42253 22 | 38048 6 | 32773 23 | 32504 24 | 26968 25 | 21154 5 | 19751 26 | 15983 27 | 11807 4 | 9841 28 | 8226 29 | 5670 3 | 4009 30 | 3722 31 | 2440 32 | 1492 2 | 1162 33 | 839 34 | 500 35 | 294 1 | 225 36 | 128 37 | 73 38 | 44 39 | 22 40 | 18 42 | 4 44 | 2 41 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT