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 | 66004 9 | 65349 11 | 62311 8 | 58295 12 | 55854 13 | 49785 19 | 46669 18 | 46381 7 | 46306 14 | 45296 20 | 45157 17 | 45078 16 | 43738 15 | 43671 21 | 42230 22 | 38201 6 | 32754 23 | 32710 24 | 26759 25 | 21046 5 | 19679 26 | 16202 27 | 11689 4 | 9859 28 | 8238 29 | 5737 3 | 4010 30 | 3740 31 | 2365 32 | 1494 2 | 1177 33 | 862 34 | 518 35 | 281 1 | 230 36 | 136 37 | 77 38 | 36 39 | 29 40 | 13 41 | 5 42 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT