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%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 | 500021 10 | 66097 9 | 65121 11 | 62102 8 | 58333 12 | 55971 13 | 49868 19 | 46675 18 | 46403 7 | 46363 20 | 45239 14 | 45099 17 | 44840 15 | 43910 16 | 43897 21 | 42113 22 | 38206 6 | 32840 23 | 32772 24 | 26754 25 | 21121 5 | 19681 26 | 16128 27 | 11681 4 | 9782 28 | 8377 29 | 5620 3 | 4036 30 | 3745 31 | 2360 32 | 1515 2 | 1162 33 | 853 34 | 495 35 | 308 1 | 227 36 | 130 37 | 63 38 | 39 39 | 23 40 | 18 41 | 5 42 | 4 45 | 1 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT