Simplified SQL and fixed problem where query result sometimes is not sorted by time.