T SQL function grouping rows in query result