SQL (Window Function)
SQL (Window Function)
ain
aly
st’
s
ALLYOUNEED
TOKNOW SERI
ES
T
oBe
come
aSu
cce
ssf
ulDa
taPr
of
es
si
ona
l
SQLFOR
DATAANALYTI
CS
WINDOW
FUNCTI
ONS
BRAINALYST - SQL SERIES
Window functions:
• Calculation scope: Window functions perform calculations on a “window” or a
subset of rows within a result set.
• Ordering: They are typically used with the ORDER BY clause to define the
window’s ordering within the result set.
• Result granularity: Window functions retain the individual rows in the result set
but can calculate values based on the window’s defined scope.
• Usage: They are used to compute values that are related to the current row
but involve other rows in the result set. Examples of window functions include
RANK, ROW_NUMBER, LAG, LEAD, and SUM with the OVER clause.
Example:
SELECT ROW_NUMBER()OVER(ORDER BY PRICE DESC) as row_
no, Price
FROM aemf2
OUTPUT:
2. RANK():
• Gives each row in a window a rank, leaving gaps for tied values.
Example:
SELECT RANK()OVER(ORDER BY PRICE DESC) as row_no,
Price
FROM aemf2;
3. DENSE_RANK():
• Gives each row in a window a rank, leaving no gaps for tied values.
Example:
SELECT DENSE_RANK()OVER(ORDER BY PRICE DESC) as row_no,
Price FROM ;
4. NTILE():
• Divides a window’s rows into a predetermined number of groups or
“tiles.”
Example:
SELECT NTILE()OVER(ORDER BY PRICE DESC) as row_no,
Price FROM ;
5. LAG():
• Accesses a previous row’s value within a window.
Example:
SELECT PRICE,LAG(PRICE)OVER(ORDER BY DAY DESC) as row_
no, Price
FROM aemf2 ;
OUTPUT:
6. LEAD():
• Accesses the value of a subsequent row within a window.
Example:
SELECT PRICE,LEAD(PRICE)OVER(ORDER BY DAY DESC) as row_
no, Price
FROM aemf2 ;
OUTPUT:
7. FIRST_Value():
• Access previous row value within window.
Example:
OUTPUT: