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 '%special%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 | 66214 9 | 65120 11 | 62197 8 | 58322 12 | 55809 13 | 49857 19 | 46692 18 | 46341 7 | 46299 20 | 45380 14 | 45244 17 | 44985 16 | 43870 15 | 43638 21 | 42196 22 | 38005 6 | 32758 23 | 32664 24 | 26897 25 | 21296 5 | 19725 26 | 16000 27 | 11756 4 | 9850 28 | 8216 29 | 5634 3 | 4000 30 | 3782 31 | 2371 32 | 1529 2 | 1170 33 | 859 34 | 495 35 | 292 1 | 228 36 | 127 37 | 78 38 | 35 39 | 26 40 | 13 41 | 7 42 | 5 45 | 1 44 | 1 (45 rows) COMMIT; COMMIT