Sample for Aggregate Window functions in SQL Server 2005 and 2008


Over clause can apply to Window functions in SQL server 2005 and 2008. The basic syntax is:
Ranking Window Functions 
<OVER_CLAUSE> :: =
    OVER ( [ PARTITION BY value_expression , ... [ n ] ]
           <ORDER BY_Clause> )

Aggregate Window Functions 
<OVER_CLAUSE> :: = 
    OVER ( [ PARTITION BY value_expression , ... [ n ] ] )
--From books online
It is required to have an ORDER BY clause for Ranking Window functions, for example, ROW_NUMBER() OVER(ORDER BY ID). PARTITION BY is optional.
Here are two samples for Aggregate Window Functions( adopted from Books Online)
USE AdventureWorks;
GO
SELECT SalesOrderID, ProductID, OrderQty
    ,SUM(OrderQty) OVER(PARTITION BY SalesOrderID) AS ‘Total’
    ,AVG(OrderQty) OVER(PARTITION BY SalesOrderID) AS ‘Avg’
    ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS ‘Count’
    ,MIN(OrderQty) OVER(PARTITION BY SalesOrderID) AS ‘Min’
    ,MAX(OrderQty) OVER(PARTITION BY SalesOrderID) AS ‘Max’
FROM Sales.SalesOrderDetail
WHERE SalesOrderID = 43664;
GO
--And another one with calculation:
USE AdventureWorks;
GO
SELECT SalesOrderID, ProductID, OrderQty
    ,SUM(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'Total'
    ,CAST(1. * OrderQty / SUM(OrderQty) OVER(PARTITION BY SalesOrderID) 
        *100 AS DECIMAL(5,2))AS 'Percent by ProductID'
FROM Sales.SalesOrderDetail 
WHERE SalesOrderID =43659;
GO
 
 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s