Created
December 10, 2012 14:57
-
-
Save dcs619/4251024 to your computer and use it in GitHub Desktop.
Date/Campus Ranking using CTE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;with rankings as ( | |
| select id, campus | |
| , dense_rank() over (partition by id, campus order by date desc ) /* frequency weight */ | |
| * ( 6 - dense_rank() over (partition by id order by date desc)) /* date weight */ | |
| as 'freqrank' | |
| from attendance | |
| ), | |
| filter as ( | |
| select id, campus, row_number() over ( | |
| partition by id | |
| order by sum(freqrank) desc | |
| ) as 'ranking' | |
| from rankings | |
| where freqrank > 0 /* limit to the last 5 recent visits */ | |
| group by id, campus | |
| ) | |
| select id, campus from filter | |
| where ranking = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment