SQL window function (Window Function)

Window can be understood as a set of records, the window function that has satisfied the special functions performed on a record set certain conditions. Window function is also known as OLAP functions, OLAP analysis that is real-time processing (Online Analytical Processing).

 

grammar:

<Window function> OVER ([PARTITION BY <grouping columns>] ORDER BY <sort column>)

(Note: by recording the set of packets is referred PARTITION BY window, without using PARTITION BY, then the entire data set as a large window.)

(Note: The window function can only be used in the SELECT clause.)

(Note: ORDER BY here is only used to determine the window function is calculated according to in what order, the sort order has no effect on the results.)

 

Window function can be used are:

1, a window function can be used as aggregate functions: SUM, AVG, COUNT, MAX, MIN

2, special window functions: RANK, DENSE_RANK, ROW_NUMBER, etc.

 

among them:

Of RANK () : calculated sorting (same rank if the record is present, then it will skip ranking, for example: 1,2,2,4)

The DENSE_RANK () : calculated sorting (even if the recording of the same rank exist, it does not skip after the ranking, for example: 1,2,2,3)

The ROW_NUMBER () : imparting continuous and single ranking, for example: 1,2,3,4

 

In addition to partition clause and order by clause, you can also add frame clause. frame is a subset of the current partition, frame clause rules to define the subset, which is generally used as a sliding window. (I.e. specify the frame: designating window for more detail.) For example:

ROW 2 PRECEDING: The first two rows

ROW 5 FOLLOWING: After five rows

ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING: a row to the front row after 1

 

The syntax summarized as follows:

window_function (expression) OVER (
   [ PARTITION BY part_list ]
   [ ORDER BY order_list ]
   [ { ROWS | RANGE } BETWEEN frame_start AND frame_end ] )

 

example:

select item_id, cate_id, rank() over (partition by cate_id order by price) as rank from item_list;
select item_id, cate_id, sum(price) over (partition by cate_id) as rank from item_list;
select item_id, cate_id, avg(price) over (order by price rows between 1 preceding and 1 following) as rank from item_list;

 

Why use the window function?

1 ranking in the group. For example, the list of statistical staff before each of the three sector wages.

2, the accumulated count. Because the window function to the current record as a benchmark statistics, can be calculated as of the current cumulative amount of orders / average order value / maximum order amount / minimum order amount / number is the number of orders, you can also add a specified framework to calculate moving average ( moving average).

 

reference:

https://ericfu.me/sql-window-function/

 

Guess you like

Origin www.cnblogs.com/HuZihu/p/12102652.html