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%accounts%' 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 | 500017 10 | 65927 9 | 65303 11 | 62521 8 | 58343 12 | 55656 13 | 49883 19 | 46725 7 | 46518 18 | 46039 14 | 45528 20 | 45390 17 | 45181 16 | 43733 15 | 43606 21 | 42424 22 | 37880 6 | 33022 23 | 32541 24 | 26696 25 | 21191 5 | 19646 26 | 15932 27 | 11608 4 | 9990 28 | 8135 29 | 5615 3 | 3986 30 | 3766 31 | 2368 32 | 1476 2 | 1188 33 | 865 34 | 490 35 | 262 1 | 237 36 | 145 37 | 84 38 | 30 39 | 25 40 | 15 41 | 5 42 | 3 45 | 2 43 | 2 44 | 1 (46 rows) COMMIT; COMMIT