溫馨提示 : 本文非小白科普文
開窗函數(shù)簡介
MYSQL 暫時(shí)還未對(duì)開窗函數(shù)給予支持。
測(cè)試數(shù)據(jù)
01、count 開窗函數(shù)
select username,product,user_type,price,
以符合條件的所有行作為窗口
count(price) over() as count1,
以按user_type分組的所有行作為窗口
count(price) over(partition byuser_type)as count2,
以按user_type分組、按price排序的所有行作為窗口
count(price) over(partition byuser_typeorder byprice) as count3,
以按user_type分組、按price排序、按當(dāng)前行+往前1行+往后2行的行作為窗口
count(price) over(partition byuser_typeorder bypricerows between1 precedingand2 following) as count4
from test;
02、sum 開窗函數(shù)
select username,product,user_type,price,
以符合條件的所有行作為窗口
sum(price) over() as sum1,
以按user_type分組的所有行作為窗口
sum(price) over(partition byuser_type) as sum2,
以按user_type分組、按price排序后、按到當(dāng)前行(含當(dāng)前行)的所有行作為窗口
sum(price) over(partition byuser_typeorder byprice) as sum3,
以按user_type分組、按price排序后、按當(dāng)前行+往前1行+往后2行的行作為窗口
sum(price) over(partition byuser_typeorder bypricerows between1 precedingand2 following) as sum4
from test;
03、min 開窗函數(shù)
select username,product,user_type,price,
以符合條件的所有行作為窗口
min(price) over() as min1,
以按classId分組的所有行作為窗口
min(price) over(partition by classId) as min2,
以按classId分組、按price排序后、按到當(dāng)前行(含當(dāng)前行)的所有行作為窗口
min(price) over(partition by classId order by price) as min3,
以按classId分組、按price排序后、按當(dāng)前行+往前1行+往后2行的行作為窗口
min(price) over(partition byclassIdorder bypricerows between1 precedingand2 following) as min4
from test;
04、max 開窗函數(shù)
select username,product,user_type,price,
以符合條件的所有行作為窗口
max(price) over() as max1,
以按classId分組的所有行作為窗口
max(price) over(partition byclassId) as max2,
以按classId分組、按price排序后、按到當(dāng)前行(含當(dāng)前行)的所有行作為窗口
max(price) over(partition byclassIdorder byprice) as max3,
以按classId分組、按price排序后、按當(dāng)前行+往前1行+往后2行的行作為窗口
max(price) over(partition byclassIdorder bypricerows between1 precedingand2 following) as max4
from test;
05、avg 開窗函數(shù)
select username,product,user_type,price,
以符合條件的所有行作為窗口
avg(price) over() as avg1,
以按classId分組的所有行作為窗口
avg(price) over(partition byclassId) as avg2,
以按classId分組、按price排序后、按到當(dāng)前行(含當(dāng)前行)的所有行作為窗口
avg(price) over(partition byclassIdorder byprice) as avg3,
以按classId分組、按price排序后、按當(dāng)前行+往前1行+往后2行的行作為窗口
avg(price) over(partition byclassIdorder bypricerows between1 precedingand2 following) as avg4
from test;
相關(guān)函數(shù)總結(jié)
- over():指定分析函數(shù)工作的數(shù)據(jù)窗口大小,這個(gè)數(shù)據(jù)窗口大小可能會(huì)隨著行的變化而變化
- preceding n:往前n行數(shù)據(jù)
- following n:往后n行數(shù)據(jù)
- current row:當(dāng)前行
- unbounded :無界限(起點(diǎn)或終點(diǎn))
- unbounded preceding:表示從前面的起點(diǎn)
- unbounded following:表示到后面的終點(diǎn)
注意:
如果不指定ROWS BETWEEN, 默認(rèn)為從起點(diǎn)到當(dāng)前行;