Jacob Wilkins - Thursday, December 7, 2017 3:36 PM
I think that you've over-complicated things here. There is no indication that there can be more than one group name, so the ROW_NUMBER() isn't needed especially since it adds an unnecessary sort. Here is a simple self-join that accomplishes the same thing.SELECT c.*
FROM #companies c
INNER JOIN #companies g
ON c.GroupNumber = g.GroupNumber
AND g.CompanyStatus = 'group'
ORDER BY g.CompanyName, c.CompanyName
;
That being said, there is another method that may perform better, because it only requires a single scan of the table (although that may be offset by an additional sort).
;
WITH Company_Groups AS
(
SELECT c.*, FIRST_VALUE(c.CompanyName) OVER(PARTITION BY c.GroupNumber ORDER BY c.CompanyStatus ROWS UNBOUNDED PRECEDING) AS GroupName
FROM #companies c
)
SELECT CompanyName, CompanyStatus, CompanyNumber, GroupNumber
FROM Company_Groups
ORDER BY GroupName, CompanyName
;
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA