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 | 66044 9 | 65034 11 | 62212 8 | 58478 12 | 55991 13 | 49600 19 | 46460 18 | 46421 7 | 46189 20 | 45494 14 | 45431 17 | 45016 16 | 44107 15 | 43510 21 | 42078 22 | 38076 6 | 32908 23 | 32664 24 | 26846 25 | 21096 5 | 19754 26 | 16092 27 | 11789 4 | 9769 28 | 8324 29 | 5643 3 | 4022 30 | 3664 31 | 2413 32 | 1555 2 | 1160 33 | 827 34 | 483 35 | 291 1 | 238 36 | 146 37 | 70 38 | 37 39 | 22 40 | 17 42 | 6 41 | 3 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT