在SQL中,OVER函數(shù)用于計(jì)算窗口函數(shù)的結(jié)果。窗口函數(shù)是一類函數(shù),用于在查詢結(jié)果的某個(gè)窗口或分組上執(zhí)行計(jì)算操作。OVER函數(shù)可以配合窗口函數(shù)使用,對(duì)查詢結(jié)果的指定分組或窗口進(jìn)行計(jì)算,并返回計(jì)算結(jié)果。
OVER函數(shù)在SELECT語句的SELECT子句中使用,其語法如下:
窗口函數(shù)() OVER (PARTITION BY 列名1, 列名2,... ORDER BY 列名3, 列名4,...)
其中,窗口函數(shù)是一種聚合函數(shù),如SUM、AVG、COUNT等等。PARTITION BY子句用于指定分組的列,ORDER BY子句用于指定排序的列。
OVER函數(shù)的作用是將查詢結(jié)果分成多個(gè)分組或窗口,并對(duì)每個(gè)分組或窗口應(yīng)用窗口函數(shù)進(jìn)行計(jì)算。它可以用于計(jì)算分組內(nèi)的累計(jì)值、排名、行號(hào)等。
舉個(gè)例子,假設(shè)有以下的Sales表:
OrderID | Product | Quantity | Price |
---|---|---|---|
1 | A | 10 | 5 |
2 | A | 5 | 10 |
3 | B | 8 | 15 |
4 | B | 12 | 20 |
如果我們想要計(jì)算每個(gè)產(chǎn)品的累計(jì)銷售量和累計(jì)銷售額,可以使用窗口函數(shù)來實(shí)現(xiàn):
SELECT OrderID, Product, Quantity, Price,
SUM(Quantity) OVER (PARTITION BY Product ORDER BY OrderID) AS TotalQuantity,
SUM(Quantity * Price) OVER (PARTITION BY Product ORDER BY OrderID) AS TotalPrice
FROM Sales;
這里,我們使用SUM函數(shù)作為窗口函數(shù),通過PARTITION BY子句將數(shù)據(jù)按照Product分組,然后按照OrderID排序。結(jié)果如下:
OrderID | Product | Quantity | Price | TotalQuantity | TotalPrice |
---|---|---|---|---|---|
1 | A | 10 | 5 | 10 | 50 |
2 | A | 5 | 10 | 15 | 100 |
3 | B | 8 | 15 | 8 | 120 |
4 | B | 12 | 20 | 20 | 360 |
可以看到,TotalQuantity列和TotalPrice列分別計(jì)算了每個(gè)產(chǎn)品的累計(jì)銷售量和累計(jì)銷售額。