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%packages%' 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 | 66132 9 | 65172 11 | 61947 8 | 58333 12 | 56098 13 | 49824 19 | 46878 18 | 46456 7 | 46350 14 | 45300 20 | 45056 17 | 44753 15 | 43836 16 | 43599 21 | 42604 22 | 37915 6 | 32831 23 | 32607 24 | 26924 25 | 21101 5 | 19616 26 | 16092 27 | 11692 4 | 9841 28 | 8350 29 | 5669 3 | 4040 30 | 3750 31 | 2354 32 | 1523 2 | 1175 33 | 849 34 | 507 35 | 296 1 | 215 36 | 132 37 | 66 38 | 45 39 | 25 40 | 12 41 | 6 42 | 3 44 | 2 43 | 2 45 | 1 (46 rows) COMMIT; COMMIT