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 '%pending%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 | 500016 10 | 66167 9 | 65130 11 | 62261 8 | 58503 12 | 55589 13 | 49957 19 | 46630 7 | 46502 18 | 46253 14 | 45341 20 | 45236 17 | 45082 16 | 44079 15 | 43647 21 | 42199 22 | 38102 6 | 33009 23 | 32506 24 | 26716 25 | 21136 5 | 19665 26 | 15961 27 | 11615 4 | 9971 28 | 8217 29 | 5602 3 | 4007 30 | 3669 31 | 2362 32 | 1514 2 | 1194 33 | 857 34 | 480 35 | 270 1 | 243 36 | 150 37 | 77 38 | 39 39 | 20 40 | 13 41 | 5 43 | 3 42 | 3 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT