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 '%unusual%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 | 500019 10 | 66152 9 | 65219 11 | 62274 8 | 58449 12 | 55719 13 | 50033 19 | 46768 7 | 46474 18 | 46344 14 | 45159 20 | 45142 17 | 44896 15 | 43947 16 | 43803 21 | 42382 22 | 38118 6 | 32773 23 | 32338 24 | 26834 25 | 20983 5 | 19862 26 | 15904 27 | 11774 4 | 9941 28 | 8137 29 | 5607 3 | 4035 30 | 3744 31 | 2331 32 | 1484 2 | 1187 33 | 867 34 | 508 35 | 260 1 | 234 36 | 133 37 | 74 38 | 44 39 | 21 40 | 13 41 | 6 42 | 4 45 | 2 43 | 2 (45 rows) COMMIT; COMMIT