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%requests%' 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 | 66333 9 | 65178 11 | 62055 8 | 58371 12 | 55917 13 | 49722 19 | 46685 7 | 46531 18 | 46392 17 | 45263 20 | 45078 14 | 45074 15 | 43981 16 | 43845 21 | 42248 22 | 37907 6 | 32920 23 | 32546 24 | 26806 25 | 20989 5 | 19881 26 | 16005 27 | 11672 4 | 9807 28 | 8240 29 | 5615 3 | 4103 30 | 3644 31 | 2362 32 | 1521 2 | 1164 33 | 845 34 | 469 35 | 284 1 | 230 36 | 139 37 | 73 38 | 38 39 | 23 40 | 12 42 | 5 41 | 4 44 | 3 43 | 1 (45 rows) COMMIT; COMMIT