I have a feeling this might end up being a simple solution but I'm spinning my wheels on it and it is driving me crazy. Here are some dummy tables I'm dealing with:NameFrequency[code="plain"]Name Role CountJack Student 3Jack Teacher 5Jack Admin 2Jack Student 2Sue Student 10Sue Teacher 4[/code]RoleRankLookup[code="plain"]Role PriorityRankTeacher 1Student 2Admin 3[/code]The goal is that I need to select the grouping of each Name and Role that have the highest counts. In the case of two groupings having the same counts, I would then need to select the Role that has the highest (lowest actual number) PriorityRank in the RoleRankLookup table. The part I have figured out is selecting the max value using this [code="sql"];WITH SumCountAS ( SELECT NAME ,[Role] ,sum([Count]) AS SumOfCount FROM NameFrequency GROUP BY NAME ,[Role] ) ,MaxCountAS ( SELECT * ,ROW_NUMBER() OVER ( PARTITION BY NAME ORDER BY SumOfCount DESC ) RN FROM SumCount )SELECT NAME ,[Role] ,SumOfCountFROM MaxCountWHERE RN = 1[/code]However, the result is only half correct because of the way the results are ordered in the MaxCount CTE. It returns the results [code="plain"]Name Role SumOfCountJack Student 5Sue Student 10[/code]The Sue Student = 10 is correct because that is the max value. However, Jack Student 5 is not the value I was looking for because both Student and Teacher have a count of 5 and I need it to select Teacher based on the PriorityRank. How can I add that check to my existing code so that it returns Jack Teacher = 5? Here is the full list of results that show the RN values in case it is of any help[code="plain"]Name Role SumOfCount RNJack Student 5 1Jack Teacher 5 2Jack Admin 2 3Sue Student 10 1Sue Teacher 4 2[/code]
↧