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 '%unusual%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 | 66025 9 | 65207 11 | 62182 8 | 58341 12 | 56083 13 | 49550 19 | 46828 7 | 46330 18 | 46204 14 | 45407 20 | 45265 17 | 45022 15 | 43847 16 | 43744 21 | 42203 22 | 38140 6 | 32703 23 | 32475 24 | 26957 25 | 21141 5 | 19740 26 | 16029 27 | 11844 4 | 9871 28 | 8147 29 | 5687 3 | 4004 30 | 3765 31 | 2403 32 | 1492 2 | 1170 33 | 852 34 | 502 35 | 294 1 | 229 36 | 129 37 | 73 38 | 43 39 | 24 40 | 17 42 | 3 41 | 3 45 | 2 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT