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%requests%' 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 | 500018 10 | 66224 9 | 65283 11 | 62075 8 | 58237 12 | 55836 13 | 49963 18 | 46601 19 | 46298 7 | 46278 20 | 45509 14 | 45205 17 | 44779 16 | 44082 15 | 43556 21 | 42351 22 | 37901 6 | 32764 23 | 32647 24 | 26890 25 | 21119 5 | 19712 26 | 16063 27 | 11844 4 | 9851 28 | 8229 29 | 5727 3 | 4016 30 | 3771 31 | 2323 32 | 1487 2 | 1179 33 | 879 34 | 502 35 | 275 1 | 226 36 | 139 37 | 67 38 | 42 39 | 23 40 | 15 42 | 5 41 | 5 44 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT