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 '%express%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 | 66127 9 | 65204 11 | 62076 8 | 58403 12 | 55836 13 | 49797 19 | 46643 7 | 46239 18 | 46202 14 | 45442 20 | 45177 17 | 44890 16 | 44026 15 | 43602 21 | 42505 22 | 38110 6 | 32692 23 | 32569 24 | 26899 25 | 21326 5 | 19649 26 | 15969 27 | 11721 4 | 9931 28 | 8275 29 | 5649 3 | 4003 30 | 3820 31 | 2328 32 | 1470 2 | 1191 33 | 863 34 | 528 35 | 277 1 | 230 36 | 149 37 | 76 38 | 38 39 | 25 40 | 10 42 | 8 41 | 3 45 | 1 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT