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 '%special%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 | 500018 10 | 66218 9 | 65200 11 | 62103 8 | 58406 12 | 55874 13 | 49681 18 | 46515 7 | 46475 19 | 46321 20 | 45433 14 | 45261 17 | 45168 15 | 43993 16 | 43878 21 | 42194 22 | 38036 6 | 33022 23 | 32347 24 | 26842 25 | 21028 5 | 19780 26 | 15917 27 | 11662 4 | 9874 28 | 8281 29 | 5626 3 | 4035 30 | 3702 31 | 2324 32 | 1472 2 | 1157 33 | 817 34 | 520 35 | 286 1 | 240 36 | 131 37 | 75 38 | 33 39 | 29 40 | 13 42 | 5 41 | 5 44 | 2 43 | 1 (45 rows) COMMIT; COMMIT