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 '%unusual%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 | 500022 10 | 66218 9 | 65293 11 | 62226 8 | 58400 12 | 55805 13 | 49706 18 | 46553 19 | 46503 7 | 46403 20 | 45405 14 | 45349 17 | 45040 16 | 43970 15 | 43651 21 | 42268 22 | 37900 6 | 32983 23 | 32490 24 | 26664 25 | 21138 5 | 19761 26 | 15971 27 | 11686 4 | 9850 28 | 8286 29 | 5573 3 | 4050 30 | 3669 31 | 2343 32 | 1460 2 | 1190 33 | 857 34 | 500 35 | 305 1 | 229 36 | 124 37 | 68 38 | 43 39 | 23 40 | 11 41 | 6 43 | 3 44 | 2 42 | 2 45 | 1 (46 rows) COMMIT; COMMIT