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 | 66091 9 | 65129 11 | 62269 8 | 58229 12 | 55780 13 | 49813 19 | 46872 7 | 46523 18 | 46030 14 | 45360 20 | 45250 17 | 45054 15 | 43931 16 | 43631 21 | 42182 22 | 38258 6 | 32718 23 | 32517 24 | 26964 25 | 21250 5 | 19614 26 | 15977 27 | 11737 4 | 9961 28 | 8149 29 | 5649 3 | 3980 30 | 3778 31 | 2421 32 | 1511 2 | 1171 33 | 857 34 | 497 35 | 285 1 | 233 36 | 136 37 | 84 38 | 36 39 | 29 40 | 12 41 | 4 42 | 3 45 | 2 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT