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%deposits%' 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 | 66065 9 | 65313 11 | 62231 8 | 58275 12 | 56033 13 | 49623 19 | 46667 18 | 46322 7 | 46249 20 | 45291 14 | 45251 17 | 45236 15 | 43755 16 | 43653 21 | 42200 22 | 38098 6 | 32795 23 | 32719 24 | 26817 25 | 21039 5 | 19748 26 | 16175 27 | 11629 4 | 9795 28 | 8343 29 | 5697 3 | 4014 30 | 3732 31 | 2355 32 | 1496 2 | 1177 33 | 860 34 | 504 35 | 297 1 | 229 36 | 129 37 | 78 38 | 34 39 | 28 40 | 13 41 | 6 42 | 5 45 | 1 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT