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 | 66058 9 | 65446 11 | 62285 8 | 58472 12 | 55665 13 | 49846 19 | 46630 18 | 46483 7 | 46384 14 | 45362 17 | 45113 20 | 45073 16 | 43771 15 | 43742 21 | 42286 22 | 38101 6 | 32865 23 | 32584 24 | 26663 25 | 21050 5 | 19774 26 | 16013 27 | 11614 4 | 9965 28 | 8143 29 | 5691 3 | 4020 30 | 3722 31 | 2314 32 | 1474 2 | 1192 33 | 852 34 | 513 35 | 275 1 | 236 36 | 132 37 | 81 38 | 38 39 | 27 40 | 11 42 | 5 41 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT