Does SQL Server support compact windowing support?
Alternative 1 - Will include all strings that bind. Will not include a line if the only lines for this Thread all are null for HitCount:
SELECT Thread, Function, HitCount FROM (SELECT Thread, Function, HitCount, MAX(HitCount) over (PARTITION BY Thread) as MaxHitCount FROM Samples WHERE FunctionId NOT IN (SELECT CalleeId FROM Callers)) t WHERE HitCount = MaxHitCount ORDER BY ThreadId, HitCount DESC
Alternative 2 - Will include all strings that bind. If there is no row for this stream with a nonzero HitCount, it will return all rows for this stream:
SELECT Thread, Function, HitCount FROM (SELECT Thread, Function, HitCount, RANK() over (PARTITION BY Thread ORDER BY HitCount DESC) as R FROM Samples WHERE FunctionId NOT IN (SELECT CalleeId FROM Callers)) t WHERE R = 1 ORDER BY ThreadId, HitCount DESC
Alternative 3 - Will not deterministically select one row in the case of links and discard others. Will include a line if all lines for this stream are null HitCount
SELECT Thread, Function, HitCount FROM (SELECT Thread, Function, HitCount, ROW_NUMBER() over (PARTITION BY Thread ORDER BY HitCount DESC) as R FROM Samples WHERE FunctionId NOT IN (SELECT CalleeId FROM Callers)) t WHERE R = 1 ORDER BY ThreadId, HitCount DESC
Alternative 4 and 5 - Uses old constructs if window functions are not available, and says that it means a little cleaner than using joins. Benchmark when it comes to priority. Both return all the lines that are involved in the tie. In Alternative 4, HitCount is null if non-zero values ββare not available for HitCount. Alternative 5 will not return rows with HitCount null.
SELECT * FROM Samples s1 WHERE FunctionId NOT IN (SELECT CalleeId FROM Callers) AND NOT EXISTS (SELECT * FROM Samples s2 WHERE s1.FunctionId = s2.FunctionId AND s1.HitCount < s2.HitCount) ORDER BY ThreadId, HitCount DESC SELECT * FROM Samples s1 WHERE FunctionId NOT IN (SELECT CalleeId FROM Callers) AND HitCount = (SELECT MAX(HitCount) FROM Samples s2 WHERE s1.FunctionId = s2.FunctionId) ORDER BY ThreadId, HitCount DESC