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 '%express%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 | 500017 10 | 65892 9 | 65318 11 | 62515 8 | 58296 12 | 55682 13 | 49871 19 | 46621 7 | 46573 18 | 46025 14 | 45493 20 | 45486 17 | 45182 16 | 43765 15 | 43646 21 | 42441 22 | 37890 6 | 33021 23 | 32526 24 | 26725 25 | 21147 5 | 19608 26 | 15934 27 | 11591 4 | 10020 28 | 8134 29 | 5664 3 | 3989 30 | 3745 31 | 2358 32 | 1490 2 | 1184 33 | 858 34 | 485 35 | 262 1 | 235 36 | 145 37 | 85 38 | 29 39 | 24 40 | 15 41 | 5 42 | 3 45 | 2 43 | 2 44 | 1 (46 rows) COMMIT; COMMIT