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 | 66111 9 | 65275 11 | 62345 8 | 58505 12 | 55598 13 | 49956 19 | 46714 18 | 46444 7 | 46383 14 | 45409 20 | 45164 17 | 44982 16 | 43991 15 | 43530 21 | 42297 22 | 38090 6 | 32939 23 | 32343 24 | 26700 25 | 21162 5 | 19708 26 | 15993 27 | 11705 4 | 9927 28 | 8207 29 | 5628 3 | 4024 30 | 3674 31 | 2304 32 | 1474 2 | 1205 33 | 862 34 | 503 35 | 301 1 | 233 36 | 131 37 | 69 38 | 50 39 | 16 40 | 13 42 | 4 41 | 4 45 | 2 43 | 2 44 | 1 (46 rows) COMMIT; COMMIT