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 | 66000 9 | 65278 11 | 62299 8 | 58266 12 | 55688 13 | 50031 19 | 46600 7 | 46512 18 | 46381 20 | 45183 14 | 45146 17 | 45015 15 | 43831 16 | 43628 21 | 42310 22 | 38230 23 | 32806 6 | 32705 24 | 26694 25 | 21239 5 | 19580 26 | 16052 27 | 11608 4 | 9938 28 | 8226 29 | 5762 3 | 3980 30 | 3757 31 | 2324 32 | 1536 2 | 1188 33 | 850 34 | 513 35 | 275 1 | 233 36 | 145 37 | 80 38 | 44 39 | 21 40 | 11 42 | 5 41 | 5 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT