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 '%pending%deposits%' 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 | 66096 9 | 65304 11 | 62134 8 | 58311 12 | 56023 13 | 49756 19 | 46646 18 | 46438 7 | 46229 20 | 45257 14 | 45193 17 | 45138 15 | 43757 16 | 43667 21 | 42191 22 | 38115 6 | 32799 23 | 32743 24 | 26761 25 | 21042 5 | 19714 26 | 16199 27 | 11655 4 | 9825 28 | 8292 29 | 5700 3 | 4018 30 | 3771 31 | 2335 32 | 1510 2 | 1180 33 | 849 34 | 516 35 | 287 1 | 228 36 | 134 37 | 76 38 | 36 39 | 27 40 | 13 41 | 6 42 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT