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 | 66003 9 | 65374 11 | 62208 8 | 58138 12 | 56027 13 | 49758 19 | 46646 18 | 46471 7 | 46309 20 | 45278 14 | 45198 17 | 45161 15 | 43869 16 | 43525 21 | 42113 22 | 38112 6 | 32827 23 | 32671 24 | 26931 25 | 20957 5 | 19773 26 | 16219 27 | 11668 4 | 9766 28 | 8311 29 | 5669 3 | 4030 30 | 3762 31 | 2356 32 | 1507 2 | 1170 33 | 844 34 | 500 35 | 304 1 | 228 36 | 128 37 | 76 38 | 37 39 | 25 40 | 17 42 | 5 41 | 5 45 | 2 43 | 1 (45 rows) COMMIT; COMMIT