over partition

Download Over Partition

If you can't read please download the document

Upload: dragan-cristina-maria

Post on 06-Feb-2016

216 views

Category:

Documents


0 download

DESCRIPTION

tion

TRANSCRIPT

OVER

OVER allows you to get aggregate information without using a GROUP BY. In other words, you can retrieve detail rows, and get aggregate data alongside it. For example, this query:

SELECT SUM(Cost) OVER () AS Cost, OrderNumFROM Orders

Will return something like this:

Cost OrderNum10.00 34510.00 34610.00 34710.00 348

Quick translation:

SUM(cost) get me the sum of the COST columnOVER for the set of rows.() that encompasses the entire result set.

OVER(PARTITION BY)

OVER, as used in our previous example, exposes the entire resultset to the aggregationCost was the sum of all [Cost] in the resultset. We can break up that resultset into partitions with the use of PARTITION BY:

SELECT SUM(Cost) OVER (PARTITION BY CustomerNo) AS Cost, OrderNum, CustomerNoFROM Orders

My partition is by CustomerNo each window of a single customers orders will be treated separately from each other window.Ill get the sum of cost for Customer 1, and then the sum for Customer 2:

Cost OrderNum CustomerNo8.00 345 18.00 346 18.00 347 12.00 348 2

The translation here is:

SUM(cost) get me the sum of the COST columnOVER for the set of rows.(PARTITION BY CustomerNo) that have the same CustomerNo.

Further Reading: BOL: OVER Clause

June 2012 edit: We highly, highly recommend Itzik Ben-Gans brand new book Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions for an outstanding and thorough explanation of windowing functions (including OVER / PARTITION BY).

Enjoy, and happy days!