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 '%express%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 | 66085 9 | 65283 11 | 62193 8 | 58481 12 | 55753 13 | 49902 19 | 46932 7 | 46474 18 | 46370 14 | 45471 20 | 45005 17 | 44780 16 | 43791 15 | 43687 21 | 42478 22 | 38067 6 | 32912 23 | 32409 24 | 26790 25 | 21090 5 | 19688 26 | 15970 27 | 11595 4 | 9991 28 | 8232 29 | 5636 3 | 4027 30 | 3730 31 | 2315 32 | 1494 2 | 1194 33 | 860 34 | 483 35 | 293 1 | 221 36 | 131 37 | 72 38 | 45 39 | 24 40 | 11 42 | 5 41 | 5 44 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT