Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed SQL Window Functions!
You have completed SQL Window Functions!
Grouping Data With Partitions
Definitions
ORDER BY β Keyword to introduce the ordering clause. Followed by expressions that determine the order of rows within the window.
Functions
These functions can only be used as window functions because they rely on the context of other rows.
- RANK() β Ranks each row based on the window functionβs ORDER BY clause
- FIRST_VALUE(expression) β Returns the value of the expression for the first record in the frame/partition
- LAST_VALUE(expression) β Returns the value of the expression for the last record in the frame/partition
- LEAD(expression,n,default) β Returns the value of the expression for the row n rows after the current row in the partition. If the specified row does not exist, returns the default value. If n is not specified, defaults to 1 (the next row)
- LAG(expression,n,default) β Returns the value of the expression for the row n rows before the current row in the partition. If the specified row does not exist, returns the default value. If n is not specified, defaults to 1 (the previous row)
Resources
See more in the PostgreSQL documentation: https://www.postgresql.org/docs/devel/static/functions-window.html
Code Example
SELECT PLAYER_NAME,
PLAYER_RANKING,
PLAYER_TEAM,
COUNT(MATCH_ID) as MATCHES_PLAYED,
SUM(CHECKMATE) as MATCHES_WON,
SUM(CHECKMATE)/COUNT(MATCH_ID) as WIN_RATE,
AVG(PLAYER_RANKING) OVER () as AVG_RANKING,
PLAYER_RANKING - AVG(PLAYER_RANKING) OVER () as DIFF_FROM_AVERAGE,
SUM(SUM(CHECKMATE)) OVER () as TOTAL_MATCHES,
SUM(MAX(CHECKMATE)) OVER () as PLAYERS_WITH_WINS,
MAX(SUM(CHECKMATE)) OVER () as HIGHEST_WINS,
SUM(SUM(CHECKMATE)) OVER (PARTITION BY PLAYER_TEAM)
/SUM(COUNT(MATCH_ID)) OVER (PARTITION BY PLAYER_TEAM) as TEAM_WIN_RATE,
MIN(PLAYER_RANKING) OVER (PARTITION BY SUM(CHECKMATE)) as TIEBREAKER,
MIN(PLAYER_RANKING) OVER (PARTITION BY SUM(CHECKMATE),
PLAYER_TEAM) as TIEBREAKER_TEAM,
RANK() OVER (PARTITION BY PLAYER_TEAM ORDER BY PLAYER_RANKING DESC) as RANKING
FROM treehouse.chess_data_matches
GROUP BY PLAYER_NAME, PLAYER_RANKING,PLAYER_TEAM
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up