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 | 66066 9 | 64960 11 | 62339 8 | 58403 12 | 56030 13 | 49606 18 | 46499 19 | 46450 7 | 46180 20 | 45476 14 | 45311 17 | 45053 16 | 43967 15 | 43659 21 | 42057 22 | 38056 6 | 32961 23 | 32672 24 | 26813 25 | 21152 5 | 19737 26 | 16041 27 | 11808 4 | 9753 28 | 8316 29 | 5688 3 | 4027 30 | 3640 31 | 2427 32 | 1532 2 | 1161 33 | 828 34 | 477 35 | 294 1 | 238 36 | 145 37 | 71 38 | 38 39 | 24 40 | 16 42 | 6 41 | 3 45 | 2 43 | 2 (45 rows) COMMIT; COMMIT