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%deposits%' 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 | 500021 10 | 66048 9 | 65387 11 | 62341 8 | 58436 12 | 55716 13 | 49862 19 | 46726 7 | 46446 18 | 46404 14 | 45309 17 | 45153 20 | 45044 16 | 43829 15 | 43699 21 | 42213 22 | 38202 6 | 32852 23 | 32518 24 | 26670 25 | 20973 5 | 19781 26 | 16080 27 | 11594 4 | 9931 28 | 8176 29 | 5696 3 | 4034 30 | 3695 31 | 2320 32 | 1480 2 | 1193 33 | 851 34 | 510 35 | 277 1 | 232 36 | 134 37 | 79 38 | 36 39 | 26 40 | 13 41 | 5 42 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT