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 | 66314 9 | 65107 11 | 62058 8 | 58361 12 | 55948 13 | 49669 19 | 46728 7 | 46367 18 | 46245 17 | 45153 14 | 45131 20 | 45120 15 | 43904 16 | 43818 21 | 42440 22 | 37822 23 | 32723 6 | 32714 24 | 26858 25 | 21129 5 | 19747 26 | 16074 27 | 11825 4 | 9793 28 | 8255 29 | 5661 3 | 4065 30 | 3721 31 | 2354 32 | 1543 2 | 1168 33 | 860 34 | 502 35 | 276 1 | 227 36 | 137 37 | 73 38 | 45 39 | 21 40 | 13 42 | 4 41 | 3 44 | 2 43 | 2 45 | 1 (46 rows) COMMIT; COMMIT