You are on page 1of 1

Parts of T-SQL

4 Window Functions
SUM(TicketSales)  OVER  
(PARTITION  BY  Show,  Year
ORDER  BY  Year,  Month
ROWS  BETWEEN  UNBOUNDED  PRECEDING  AND  CURRENT  ROW)

Window Function + Over


1 Begin  with  a  function  like  SUM(),  LAG(),  or  ROW_NUMBER(),  followed  by  
OVER().  The  OVER()  clause  is  a  container  that  lets  SQL  Server  know  we’re  
using  a  window  function.

Partition By
2 PARTITION  BY  tells  the  function  when  to  reset  the  counter.  It  means,  “For  
each  unique  value  in  the  partitioned  columns,  run  this  function.”  If  we  
partition  by  Show  and  Year,  the  function  will  count  until  it  reaches  the  
next  year  for  that  Show,  or  a  new  Show,  and  then  reset.

Order By
3 ORDER  BY  in  a  window  function  applies  only  to  that  function  as  it  
calculates  its  result  – it  does  not  change  the  order  of  the  final  result  set.  
You  can  have  multiple  window  functions  with  different  ORDER  BY  clauses  
in  the  same  result  set.  ORDER  BY  is  required  for  ranking  functions,  but  
optional  for  most  others.

Rows Between
4 ROWS  BETWEEN  can  further  limit  the  scope  of  a  function  by  telling  it  to  
only  look  a  certain  number  of  rows  ahead  or  behind.  The  three  options  
are  PRECEDING,  CURRENT  ROW,  and  FOLLOWING.  If  using  PRECEDING  or  
FOLLOWING,  specify  either  a  number  of  rows  or  no  limit  with  the  word  
UNBOUNDED.  ROWS  BETWEEN  is  an  easy  way  of  generating  running  
totals  like  year-­‐to-­‐date  (YTD)  numbers.

©  SQLTheater.com

You might also like