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 | 500024 10 | 66102 9 | 65175 11 | 62219 8 | 58187 12 | 55670 13 | 50080 19 | 46715 7 | 46578 18 | 46341 20 | 45233 14 | 45168 17 | 44947 15 | 43764 16 | 43731 21 | 42363 22 | 38100 6 | 32773 23 | 32660 24 | 26796 25 | 21257 5 | 19528 26 | 16120 27 | 11688 4 | 9896 28 | 8235 29 | 5710 3 | 3975 30 | 3710 31 | 2358 32 | 1482 2 | 1212 33 | 858 34 | 509 35 | 295 1 | 231 36 | 143 37 | 77 38 | 46 39 | 19 40 | 11 41 | 6 42 | 3 43 | 2 46 | 1 45 | 1 44 | 1 (47 rows) COMMIT; COMMIT