Windowing functions - Kevin Boles

Preview:

DESCRIPTION

Presentation from Kevin Boles at SQL In The City US Tour 2013.

Citation preview

•–

•–

• PARTITION BY -

• ORDER BY -

• ROWS | RANGE -

OVER( [ <PARTITION BY clause> ]

[ <ORDER BY clause> ]

[ <ROW or RANGE clause> ] )

• scalar_expression –

• OVER –

LAST_VALUE(scalar_expression)

OVER ([partition_by_clause] order_by_clause)

SELECT OrderID, CustomerID,

FIRST_VALUE(OrderID) OVER(PARTITION BY CustomerID ORDER BY OrderID

ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

AS FirstOrderID

FROM dbo.Orders

WHERE CustomerID IN (1,2)

SELECT OrderID, CustomerID,

LAST_VALUE(OrderID) OVER(PARTITION BY CustomerID ORDER BY OrderID

ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

AS FirstOrderID

FROM dbo.Orders

WHERE CustomerID IN (1,2)

SELECT st1.[Date], st1.TicketCount,RunningTotal = SUM(st2.TicketCount)

FROM dbo.SpeedingTickets AS st1 INNER JOIN dbo.SpeedingTickets AS st2

ON st2.[Date] <= st1.[Date] GROUP BY st1.[Date], st1.TicketCount ORDER BY st1.[Date];

From Aaron Bertrand

SELECT [Date], TicketCount, RunningTotal = TicketCount +

COALESCE(( SELECT SUM(TicketCount) FROM dbo.SpeedingTickets AS s

WHERE s.[Date] < o.[Date]), 0 )FROM dbo.SpeedingTickets AS o ORDER BY [Date];

• scalar_expression –

• Offset –

• Default –

• OVER –

LAG (scalar_expression [,offset] [,default])

OVER ([partition_by_clause] order_by_clause)

CUME_DIST ( ) OVER

([ partition_by_clause ] order_by_clause)

PERCENT_RANK ( ) OVER

([ partition_by_clause ] order_by_clause)

PERCENTILE_DISC ( numeric_literal) WITHIN GROUP ( ORDER BY expression) OVER ([<partition_by_clause> ] )

PERCENTILE_CONT ( numeric_literal) WITHIN GROUP ( ORDER BY expression) OVER ([<partition_by_clause> ] )

Deck by Shy Engelberg and Kevin Boles