mastering t-sql window functions
TRANSCRIPT
http://msdn.microsoft.com/en-us/library/ms189461(v=sql.110).aspx
OVER (<PARTITION BY clause><ORDER BY clause><ROW or RANGE clause>)
Divide the query result set
into partitions and the
operation is applied to each
partition separately
Defines the logical order of
the rows within each partition
of the result set
Limits the rows within the
partition by specifying start
and end points within the
partition
ID AcctID TransDate TransAmt
1 1234 27/11/2012 $150.00
2 1234 27/11/2012 $22.00
3 5678 28/11/2012 $50.00
4 5678 28/11/2012 $150.00
5 5678 28/11/2012 $10.00
6 5678 29/11/2012 $120.00
7 0987 30/11/2012 $20.00
8 0987 30/11/2012 $100.00
9 0987 30/11/2012 $50.00
Aggregation Window:SUM(TransAmt) OVER(PARTITION BY TransDate)
Ranking Window:ROW_NUMBER() OVER(PARTITION BY TransDate
ORDER BY AcctID, ID)
AcctID TransDate TransAmt BalAmt
5678 28/11/2012 $50.00 $50.00
5678 28/11/2012 $150.00 $200.00
5678 28/11/2012 $10.00 $210.00
AcctID TransDate TransAmt BalAmt Rank
5678 28/11/2012 $50.00 $50.00 1
5678 28/11/2012 $150.00 $200.00 2
5678 28/11/2012 $10.00 $210.00 3
AcctID TransDate TransAmt
5678 28/11/2012 $50.00
5678 28/11/2012 $150.00
5678 28/11/2012 $10.00
Ranking Aggregation Analytic
ROW_NUMBER()
RANK()
DENSE_RANK()
NTILE()
SUM() | AVG() | COUNT()
MIN() | MAX()
CHECKSUM_AGG
STDEV() | STDEVP()
VAR() | VARP()
LEAD() | LAG()
FIRST_VALUE() | LAST_VALUE()
CUME_DIST()
PERCENT_RANK()
PERCENTILE_DIST()
PERCENTILE_CONT()
No Framing
Available
DEMO
DEMO
No Framing
Available
LEAD | LAG
(scalar_expression [,offset] [,default])
OVER ( [ partition_by_clause ]
order_by_clause )
FIRST_VALUE | LAST_VALUE
( [scalar_expression] )
OVER ( [ partition_by_clause ]
order_by_clause
rows_range_clause )
No Framing
Available
CUME_DIST()
OVER ( [ partition_by_clause ]
order_by_clause )
No Framing
Available
PERCENT_RANK()
OVER ( [ partition_by_clause ]
order_by_clause )
No Framing
Available
PERCENTILE_DIST ( numeric_literal )
WITHIN GROUP ( ORDER BY order_by_expression [ ASC | DESC ] )
OVER ( [ partition_by_clause ]
order_by_clause
rows_range_clause )
No Framing
Available
PERCENTILE_CONT ( numeric_literal )
WITHIN GROUP ( ORDER BY order_by_expression [ ASC | DESC ] )
OVER ( [ partition_by_clause ]
order_by_clause
rows_range_clause )
DEMO