Use window functions in postgres instead of double query to support pagination